I'm trying to figure out a way of how to be able to assign a function pointer to functions with different number of arguments.
I have a while loop which takes a number of different functions as a conditional statement, so instead of writing multiple while loops with exactly the same code inside I'd like to have one with a function pointer. All the functions are of format bool f(...)
. I think some code will best illustrate what I mean:
int a, b, c, d;
MyClass* my_class;
typedef bool (MyClass::*my_fun_t)();
my_fun_t my_fun;
if (condition1)
my_fun = &MyClass::function_one();
else if (condition2)
my_fun = &MyClass::function_two(a, b);
else if (condition3)
my_fun = &MyClass::function_three(a, b, c);
else if (condition4)
my_fun = &MyClass::function_four(a, b, c, d);
while ((my_class->*my_fun)())
{ ... }
Now this obviously doesn't work because the functions have different signatures. Is it at all possible to make it work in a similar fashion? Are functoids something I should look at?
You can’t. Function pointers are specific to one function signature. This is entirely logical: how would you invoke such a function? (Yes, C allows invoking functions without specifying in their declaration how many parameters the function has, but this doesn’t work in C++ since it subverts the type system.)
Generally yes, but they don’t solve this problem.
You want
std::function
, a polymorphic function object, andstd::bind
to create function objects by binding arguments to the parameters of other functors.If you can't use C++11, then
boost::function
andboost::bind
are equivalent, although slightly more restrictive.This works for me:
Output:
Obviously you CAN declare and use function pointers for (member-)functions using variable arguments.
You could use
std::function<>
andstd::bind()
.These assumes you will use C++11. If you can't use C++11 but can use TR1, replace all
std::
withstd::tr1::
. There is also a Boost implementation.