Forcing an overload selection at the callee site

Viewed 32

Given the code:

#include <iostream>
#include <functional>
#include <type_traits>

using ftype = int ( int ) ;
using function_type = std::function<ftype> ;

struct STest
    {
    STest(bool b) { }
    STest(function_type f) { }
    };
    
int AFunction ( int parm )
    {
    return (parm + 1);
    }

int main() 
    {
    STest ss(&AFunction);
    return 0;
    }

the construction of 'ss' in the main() unction causes the constructor taking a bool to be used, where I want the constructor taking a function_type to be used. Obviously I can solve this problem at the caller site by changing:

STest ss(&AFunction);

to

STest ss(static_cast<function_type>(&AFunction));

and the constructor taking a function_type will be used. But is there any way I can change the code at the callee site in the STest struct so that the constructor taking a function type will be used, even if I just specify STest ss(&AFunction); as the code, without changing the types that each constructor takes.

2 Answers

It seems that your only stated requirement is not to change the existing constructors.

But you didn't say anything about not adding another overload:

STest(ftype f) : STest{function_type{f}} {}

The correct overload gets delegated to.

You can change your function type from std::function to a function pointer:

using function_type = int(*)(int);

Now STest(function_type f) can be called without a need for casting, and so it's always prefered over STest(bool b).

Related