'how could I achieve something like std::function<bool(int, int=1)> that would able to point to bool f(int)?
as the question asks, I know that function pointer as written cannot be compiled. But is it possible to achieve something like std::function<bool(int, int=1)> ?
Which I would like to point to both types of function bool A(int, int) and bool A(int)
A example:
// not compliable
std::function<bool(int, int=1)> funct_ptr;
bool A(int i, int j)
{
return true;
}
bool B(int i)
{
return true;
}
bool C(int i, int j = 1)
{
return true;
}
// have funct_ptr point to each function and call it
funct_ptr = A;
funct_ptr(1,1); // returns true
funct_ptr = B;
funct_ptr(1); // returns true
funct_ptr = C;
funct_ptr(1,1); // returns true
funct_ptr(1); // returns true
Solution 1:[1]
C++ is type-safe and statically typed, unlike e.g. Python. The allowed arguments of func_ptr::operator() do not depend on the runtime value of func_ptr, just on the compile-time type of func_ptr.
In your question, assigning A, B or C cannot vary the type of func_ptr.
But let's take back one step. You can define your own class which has an overloaded operator(), with one overload taking (int) and the other taking (int,int). Internally, your class can contain a std::variant< std::function<void(int)>, std::function<void(int,int)> >.
And it's up to you how you connect the two operator() of your class to the two possible function pointer types internally. If your operator()(int) is called, but the variant contains a std::function<void(int,int)>, you can of course add an 1 for the extra missing argument.
I don't know how you want to handle a call to operator()(int,int) when the variant only contains a std::function<void(int)>. Throw an exception? Silently discard the extra argument? It's up to you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MSalters |
