如何将派生类中的成员函数作为回调传递?

L3M*_*M0L 1 c++ callback c++11

我有一个简单的课程 X

class X {
public:
    template<typename T>
    void doSomething(T &completion) {
        std::cout << completion(10) << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

和一类AB

class A {
public: 
 // some code
 X* c;
};

class B : public A {
public:
  int test(int x) {
    return x * x;
  }

  void execute() {
   auto lambda = [] (int x) { cout << x * 50 << endl; return x * 100; };
   c->doSomething(lambda); // works
   c->doSomething(&B::test); // does not work
  }
};
Run Code Online (Sandbox Code Playgroud)

我想传递给doSomething方法一个类的成员方法B(或从中派生的任何其他类A),但它只是不起作用:/

Rei*_*ica 5

如何将派生类中的成员函数作为回调传递?

你的问题与B儿童班无关.您的问题是您没有将非静态成员函数绑定到其实例. test()

您可以通过使用std::bind返回仿函数轻松解决此问题:

c->doSomething(std::bind(&B::test, this, std::placeholders::_1));
Run Code Online (Sandbox Code Playgroud)

别忘了#include <functional>,

或使用拉姆达通过把包裹呼叫this拉姆达捕获:

c->doSomething([this](int x){ return this->test(x); });
Run Code Online (Sandbox Code Playgroud)

注意:确保将doSomething()参数更改为右值引用,以便它可以在两个临时对象中正确地获取所有这些回调优点.应该是这样的:

template<typename T>
void doSomething(T&& completion)
Run Code Online (Sandbox Code Playgroud)