#include "iostream"
#include <map>
#include <string>
#include <functional>
using namespace std;
class NonCopyable
{
protected:
NonCopyable() = default;
~NonCopyable() = default;
NonCopyable(const NonCopyable& ) = delete;
NonCopyable& operator = (const NonCopyable& ) =delete;
};
template<class Func>
class Events : NonCopyable
{
public:
Events(){}
~Events(){}
int Connect(Func&& f)
{
return Register(f);
}
int Connect(const Func& f)
{
return Register(f);
}
void DisConnect(int key)
{
m_connections.erase(key);
}
template <class ...Args>
void Notify(Args&& ...args)
{
for(auto& it : m_connections)
{
it.second(std::forward<Args>(args)...);
}
}
private:
template<class F>
int Register(F&& f)
{
int k = m_observerId++;
m_connections.emplace(k, std::forward<F>(f));
return k;
}
private:
int m_observerId = 0;
std::map<int, Func> m_connections;
};
struct Add
{
int a, b;
void print(int a, int b)
{
cout << "Add a: " << a << "b: " << b <<endl;
}
};
void print(int a, int b)
{
cout << "Func a: " << a << "b: " << b <<endl;
}
int main()
{
Events<std::function<void(int,int)>> myEvents;
auto key = myEvents.Connect(print);
Add add;
auto addFunc = std::bind(&Add::print, &add, std::placeholders::_1,std::placeholders::_2);
auto addKey = myEvents.Connect(addFunc);
auto lamdaKey = myEvents.Connect([&add](int a, int b){
add.a = a;
add.b = b;
cout << "lamda a: " << a << "b: " << b <<endl;
});
int a = 1;
int b = 2;
myEvents.Notify(a,b);
myEvents.DisConnect(key);
getchar();
return 0;
}
C++ 11实现观察者模式
于 2022-11-28 20:23:00 首次发布
本文介绍了一个不可复制的事件处理类模板,展示了如何使用`std::function`和`lambda表达式`实现事件连接、断开和通知。重点讲解了`NonCopyable`类和`Events`模板类的用法,以及如何通过绑定函数到事件中。

675

被折叠的 条评论
为什么被折叠?



