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

标签 c++ c++11 callback

我有一个简单的类 X

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

和一个类 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
  }
};

我想向 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/

相关文章:

c++ - 编译器对析构函数省略的自由度是多少?

c++ - C++ 中的函数式编程。实现 f(a)(b)(c)

ios - 仅使用 inNumberFrames 信息在 AudioBufferList 中分配缓冲区 iOS

c++ - wxWidgets 在其他机器上运行

c++ - 如何在 C++ 中使用 boost 创建线程池?

c++ - 从原始指针创建 shared_ptr 的链表

javascript - 如何在两个单独的函数中使用 JavaScript 变量?

javascript - TinyMCE:事件初始化后如何绑定(bind)

c++ - 串行 channel 上的 boost::asio::async_write 问题

c++ - 编译器如何传递 `std::initializer_list` 值? (或 : how can I get around a universal overload with one? )