将std :: function绑定到不同的类成员函数

时间:2019-03-14 15:27:45

标签: c++ function callback bind

我有一个CallbackUser类,它需要存储对A类的函数或对A的子类B的函数的回调。

我希望CallbackUser将回调存储为std :: function,这样在发出回调时它不需要做任何特殊处理或dynamic_casting。 CallbackUser会将回调作为std :: function绑定到其对象,并在不知道内部内容的情况下调用它。

CallbackUser是否可以通过某种方式对A及其子类进行多态回调,而不必知道其实际调用的是哪个类或方法?

callback.h

class A {
public:
    A() {};
    void method1() { cout << "method1" << endl; }
    void method2() { cout << "method2" << endl; }
};

class B : public A {
public:
    B() {};
    void derived1() { cout << "derived1" << endl; }
    void derived2() { cout << "derived2" << endl; }
};

class CallbackUser {
public:
    CallbackUser() {};
    void set(
        function< void (void) > const& callback,
        A* target
    ) {
        myCallback = bind( callback, target );
    }
    void issueCallback() {
        myCallback();
    }

private:
    std::function< void () > myCallback;
};

callback.cpp

#include "callback.h"

int main() {
    A* a               = new A;
    B* b               = new B;
    CallbackUser* user = new CallbackUser;

    std::function< void (void) > callback;

    callback = std::bind( &A::method1, a);
    user->set( callback, a );
    user->issueCallback();

    callback = &B::method1;
    user->set( callback, b );
    user->issue();
}

绑定期间的编译错误:

function not viable: no known conversion from '__bind<const std::__1::function<void ()> &, A
  *&>' to 'const std::__1::function<void ()>' for 1st argument

0 个答案:

没有答案