Reputation: 307
I want to do something like this:
typedef int(A::*f_ptr)(int);
class A
{
int f1(int a){ /*do something*/ }
int f2(int a){ /*do something else*/ }
f_ptr pick_f(int i)
{
if(i)
return this->f1;
return this->f2;
}
}
The reason is that I want instances of class A to hold certain useful variables and later on to just pick the member functions that I need depending on user input. But this does not work because I get the "a pointer to a bound function can only be used to call the function". How can I write a function that returns a pointer to a non-static member function?
Upvotes: 3
Views: 194
Reputation: 60228
You need to return the address of the member functions, like this:
f_ptr pick_f(int i)
{
if(i)
return &A::f1;
return &A::f2;
}
Or the equivalent terser version:
f_ptr pick_f(int i)
{
return i ? &A::f1 : &A::f2;
}
Upvotes: 7