C++ 通用模版消息订阅模式

        C++中消息订阅模式的处理过程,针对不同的消息处理的数据不同,如果通过类型继承处理,需要写很多的类型,通过模版会减少代码的编写。

        在学习别人的代码的时候,看见了这种模式,感觉挺好做个笔记。

#include <iostream>
#include <functional>
#include <map>
using namespace std;

enum EventType{
    ADD,
    SUB,
    MUL,
    DIV
};

template<class T, class ...Args>
class EventDelegate{
public:
    EventDelegate(){}
    ~EventDelegate(){}

    size_t Subscribe(function<void(T, Args...)> func){
        _map[_id++] = func;
        return _id;
    }

    void Unubscribe(size_t id){
        _map.erase(id);
    }

    void Fire(T t){
        for(auto& iter: _map){
            iter.second(t); 
        }
    }

private:
    size_t _id = 0;
    map<size_t, function<void(T, Args...)>> _map;
};

template<class T, class ...Args>
class EventManager {
public:
    static EventDelegate<T, Args...> _event;
};

template<class T, class ...Args>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值