我有一个简单的类 X
class X {
public:
template<typename T>
void doSomething(T &completion) {
std::cout << completion(10) << std::endl;
}
};
和一个类 A
和 B
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
}
};
我想向 doSomething
方法传递 B
类(或从 A
派生的任何其他类)的成员方法,但它只是不起作用:/
最佳答案
How can I pass a member function from a derived class as a callback?
您的问题与B
无关作为一个 child 类。你的问题是你没有绑定(bind) 非静态成员函数 test()
到它的实例。
您可以通过 using std::bind
轻松解决此问题返回一个仿函数:
c->doSomething(std::bind(&B::test, this, std::placeholders::_1));
别忘了 #include <functional>
,
或使用 lambda 通过放置 this
来包装调用在lambda captures :
c->doSomething([this](int x){ return this->test(x); });
注意:确保更改doSomething()
的参数是一个右值引用,这样它就可以在临时对象和其他对象中正确地利用所有这些回调的好处。应该看起来像这样:
template<typename T>
void doSomething(T&& completion)
关于c++ - 如何将派生类的成员函数作为回调传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52130845/