标签:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <functional>
#include <map>
#include <algorithm>
using namespace std;
class NonCopyable {
protected:
NonCopyable() = default;
~NonCopyable()=default;
NonCopyable(const NonCopyable& ) =delete;
NonCopyable& operator=(const NonCopyable&)=delete; };
template<typename Func>
class Events : NonCopyable {
private:
int m_observerId =0;// 观察者对应的编号
std::map<int, Func> m_connections; //观察者列表
//保存观察者并分配观察者的编号
template<typename F>
int Assign2(F&& f) {
int k = m_observerId++;
m_connections.emplace(k, std::forward<F>(f));
return k;
}
public:
Events(){};
~Events(){}
// 注册观察者 支持右值引用
int Connect(Func&& f) { return Assign2(f); }
// 注册观察者
int Connect(const Func& f) { return Assign2(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)...);
}
};
struct stA{
int a, b;
void print(int a, int b){ cout<<a<<", "<<b<<endl; }
void print2(){ cout<<a<<", "<<b<<endl; }
};
void print(int a, int b){ cout<<a<<", "<<b<<endl;}
void test1() {
Events<std::function<void(int, int)>> myevent;
auto key = myevent.Connect(print);//以函数方式注册观察者
stA t;
auto lambdakey = myevent.Connect([&t](int a, int b){ t.a=a; t.b=b; t.print2(); });
//auto lambdakey = myevent.Connect([&t](int a, int b){ t.a=a; t.b=b;});
std::function<void(int,int)> f = std::bind(&stA::print,&t, std::placeholders::_1,std::placeholders::_2);
myevent.Connect(f);
int a=11, b=12;
myevent.Notify(a,b);
cout<<"key = "<<key<<endl;
myevent.Disconnect(key);
}
int main()
{
test1();
return 0;
}
标签:
原文地址:http://my.oschina.net/u/1178070/blog/513846