简体   繁体   English

具有对象成员回调的std函数

[英]std function with object member callback

I have a class that fires events, and I want to handle those event in another class. 我有一个引发事件的类,并且我想在另一个类中处理那些事件。 The following code shows what I am trying to achieve: 以下代码显示了我要实现的目标:

#include <functional>

using namespace std;

class StatusReport {
public:
    int value;
};

class Sender {
public:
    function<void(StatusReport *report)> ReportEvent;

    void test() {
        StatusReport *r = new StatusReport();
        ReportEvent(r);
    }
};


class Receiver {
public:
    Receiver() {
        Sender s = Sender();
        s.ReportEvent = std::bind(&Receiver::StatusReportEvent, this);
    }

    void StatusReportEvent(StatusReport *report) {
    }
};

int main() {
    Receiver r();
    return 0;
}

This generates an error when I try to bind the event to a method inside my receiver object. 当我尝试将事件绑定到接收器对象内的方法时,这会产生错误。 The error is 错误是

no match for call to ‘(std::_Bind<std::_Mem_fn<void (Receiver::*)(StatusReport*)>(Receiver*)>) (StatusReport*)’

What am I doing wrong here? 我在这里做错了什么?

Since your function receives argument of type StatusReport bind should be called like 由于您的函数接收到StatusReport类型的参数,因此应按以下方式调用bind

s.ReportEvent = std::bind
(
   &Receiver::StatusReportEvent, this, std::placeholders::_1
);

std::placeholders::_1 is a placeholder for argument. std::placeholders::_1是参数的占位符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在类成员中使用std :: bind和std :: function会导致回调使用旧对象引用? - Using std::bind and std::function with a class member causes the callback to use an old object reference? std :: function到对象的成员函数和对象的生命周期 - std::function to member function of object and lifetime of object 使用std :: tr1 :: function的成员回调函数出现“ No Match”错误 - 'No Match' Errors with a member callback function using std::tr1::function 没有可行的重载&#39;=&#39;来分配std :: function回调作为成员函数 - No viable overloaded '=' for assigning std::function callback as member function 使用std :: bind将类成员函数注册为函数的回调 - Registering a class member function as a callback to a function using std::bind C ++-使用std :: function将成员函数传递给成员对象 - C++ - Pass member function to member object with std::function std :: bind参数绑定到没有对象的成员函数 - std::bind parameter to member function without object 指向std :: invoke中成员函数对象的指针 - Pointer to member function-object in std::invoke 如何使用std :: bind将成员函数设置为回调 - How to set a member function as callback using std::bind glfw输入回调以使用成员函数修改对象 - glfw input callback to modify an object with a member function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM