c++11版实现事件处理类支持广播,不限制函数参数,支持返回值,支持Lambda表达式

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();
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值