c++11版实现事件处理类支持广播,不限制函数参数,支持返回值,支持Lambda表达式
Events.h文件
/*
这是一个事件处理函数
支持广播执行全部函数
*/
#ifndef EVENT_H
#define EVENT_H
#include <map>
#include <future>
#include <functional>
class Events
{
using Event = std::function<void()>;
public:
Events();
~Events();
public:
//增加事件函数 可覆盖
template<typename FUNC, typename... Args>
auto Add(std::string strKey,FUNC&& func, Args&&... args)->std::future<decltype(func(args...))> {
using ReturnType = decltype(func(args...));
auto curEvent = std::make_shared<std::packaged_task<ReturnType()>>(std::bind(std::forward<FUNC>(func), std::forward<Args>(args)...));
std::future<ReturnType> future = curEvent->get_future();
eventFun[strKey] = std::bind(&std::packaged_task<ReturnType()>::operator(), curEvent);//压入数据
return future;
}
//移除事件函数
void Remove(std::string strKey);
//执行指定事件函数
bool Run(std::string strKey);
//广播执行事件函数
void RunAll();
private:
std::map<std::string, Event> eventFun;
};
#endif // !EVENT_H
Events.cpp文件
#include "Events.h"
Events::Events()
{
}
Events::~Events()
{
}
void Events::Remove(std::string strKey)
{
auto it = eventFun.find(strKey);
if (it != eventFun.end())
{
eventFun.erase(it);
}
}
bool Events::Run(std::string strKey)
{
auto it = eventFun.find(strKey);
if (it != eventFun.end())
{
it->second();
return true;
}
return false;
}
void Events::RunAll()
{
for (auto &it : eventFun)
{
it.second();
}
}
测试方法
#include <iostream>
#include "Event.h"
int test1(int num){
prinf("%d\n",num);
return 100;
}
int main(int argc, char *argv[])
{
Events evens;
auto u = evens.Add("1", test1, 2);
auto h = evens.Add("2", [] { printf("hello!\n"); });
evens.RunAll();
}