繁体   English   中英

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

[英]std function with object member callback

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

#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*)’

我在这里做错了什么?

由于您的函数接收到StatusReport类型的参数,因此应按以下方式调用bind

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

std::placeholders::_1是参数的占位符

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM