[英]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.