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

时间:2014-12-09 14:38:20

标签: c++ event-handling

我有一个触发事件的类,我想在另一个类中处理这些事件。以下代码显示了我想要实现的目标:

#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;
}

当我尝试将事件绑定到接收器对象内的方法时,会生成错误。错误是

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

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

由于您的函数接收类型StatusReport的参数,因此应该像

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

std::placeholders::_1是参数的placeholder