简体   繁体   中英

C++: How to return a pointer to a non-static member function?

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM