引自:https://blog.csdn.net/SuperYang_/article/details/79041345
引自:https://blog.csdn.net/gx864102252/article/details/80739885?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-5.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-5.control
template<typename Func>
class Events
{
public:
//注册观察者
int connect(Func&& f)
{
return assgin(f);
}
//注册观察者
int connect(const Func& f)
{
return assgin(f);
}
//移除观察者
void disconnect(int key)
{
m_connections.erase(key);
}
//通知所有的观察者
template<typename ...Args>
void notify(Args...args)
{
for (auto& it : m_connections)
{
//入参传入所有的观察者,需要入参保存一致
it.second(std::forward<Args>(args)...);
}
}
private:
template<typename F>
int assgin(F &&f)
{
int k = m_observerId++;
m_connections.emplace(k, std::forward<F>(f));
return k;
}
int m_observerId = 0; //观察者号
std::map<int, Func> m_connections; //观察者列表
};
struct StA
{
int a, b;
void print(int a, int b)
{
cout << a << "," << b << endl;
}
};
void print(int a, int b)
{
cout << a << "," << b << endl;
}
int main()
{
Events<std::function<void(int, int)>> evt;
//函数方式注册观察者
auto key = evt.connect(print);
//lambda注册,修改对象数据
StA t;
auto lambdakey = evt.connect([&t](int a, int b) {t.a = a; t.b = b; });
//functional
std::function<void(int, int)> f = std::bind(&StA::print, &t, std::placeholders::_1, std::placeholders::_2);
evt.connect(f);
int a = 1, b = 2;
evt.notify(a, b);
cout << t.a << "," << t.b << endl;
getchar();
return 0;
}