C++ How to make function pointer to class method

前端 未结 3 993
时光说笑
时光说笑 2020-12-04 02:18

I\'m having trouble making a function pointer to a class method. I made a function pointer to a non-class method and it works fine.

int foo(){
    return 5;
         


        
3条回答
  •  感动是毒
    2020-12-04 03:14

    Just found out you can do

    #include 
    #include 
    
    using namespace std;
    
    struct Foo {
       int x;
       int foo() { return x; }
    };
    
    int main() {
      function f = &Foo::foo;
      Foo foo = { 3 };
      assert(f(foo) == 3);
      foo.x = 5;
      assert(f(foo) == 5);
    }
    

    std::mem_fn() might work too: https://en.cppreference.com/w/cpp/utility/functional/mem_fn

提交回复
热议问题