我想在使用合成时将成员类事件绑定(bind)到消费者类函数。如果问题描述错误,请纠正我,我来自C#背景。
这是代码:
#include "stdafx.h"
#include <functional>
#include <iostream>
using namespace std::placeholders;
class Observable
{
public:
void Register(std::function<void()> Callback)
{
}
std::function<void()> OnStateChanged;
void ChangeState()
{
std::cout << "DevicioClient::ChangeState" << std::endl;
OnStateChanged();
}
};
class Observer
{
Observable client;
void OnStateChanged()
{
std::cout << "DevicioConsumer::OnStateChanged" << std::endl;
}
public:
void Run()
{
// does work
client.OnStateChanged = []{
std::cout << "client.OnStateChanged" << std::endl;
};
// doesn't work
// OnStateChanged = std::bind(&Observable::OnStateChanged, this);
client.ChangeState();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Observer consumer;
consumer.Run();
getchar();
return 0;
}
我想在Observable调用OnStateChanged函数时运行Observer::OnStateChanged。
最佳答案
它为您尝试绑定(bind)的功能显示&Observable::OnStateChanged
...您是说&Observer::OnStateChanged
吗?因为这样可以正常工作:
client.OnStateChanged = std::bind(&Observer::OnStateChanged, this);
关于c++ - C++ 0x11-std::bind和composition,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33460700/