将方法作为其他方法回调参数传递

Pass method as other method callback parameter

我正在尝试将一个方法作为另一个方法的回调,就像这样:

Actions actions;
Button button;

int main()
{
    actions = Actions();
    button = Button();
    
    button.onClick(actions.doSmthg);

    return 0;
}

这是我的 Actions:

class Actions {
  public:
    Actions();
    void doSmthg();
};

这里是 Button 我尝试实现回调模式:

class Button {
  public:
    Button() {};
    void onClick(void (*callbackPtr)());
};

遗憾的是我收到以下错误:

error: invalid use of non-static member function ‘void Actions::doSmthg()’

我检查了多个建议在处理回调时使用 std::bind 的示例,但我真的不确定如何让它工作。

有在 C++ 中实现这种模式的想法吗?

这是一个实时沙箱 https://onlinegdb.com/nL3SIUOaI

方法一

您可以使用 std::bindstd::function,如下所示:

#include <iostream>
#include <functional>
class Actions {
  public:
    Actions(){}
    void doSmthg(){
        std::cout<<"do something called"<<std::endl;
    }
};
class Button {
  public:
    Button() {};
    void setFunc(std::function<void ()> eventFunction) { fn = eventFunction; }

    void onClick(){
        std::cout<<"button clicked"<<std::endl;
        //call the function on the passed object
        fn();
        
    }
    private:
     std::function<void ()> fn;
};

int main()
{
    Actions action;
    Button button;
    button.setFunc(std::bind(&Actions::doSmthg, action));
    
    button.onClick();

    return 0;
}

上面程序的输出可见here:

button clicked
do something called

方法二

这里我们把onClick成员函数做成成员函数模板.

#include <iostream>

class Actions {
  public:
    Actions(){}
    void doSmthg(){
        std::cout<<"do something called"<<std::endl;
    }
};
class Button {
  public:
    Button() {};
    template<typename T>
    void onClick(void (T::*callbackPtr)(), T obj){
        std::cout<<"button clicked"<<std::endl;
        //call the function on the passed object
        (obj.*callbackPtr)();
    }
};
int main()
{
    Actions action;
    Button button;;
    
    button.onClick<Actions>(&Actions::doSmthg, action);

    return 0;
}

上面程序的输出可见here:

button clicked
do something called