forked from qicosmos/cosmos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MessageBus.hpp
71 lines (64 loc) · 1.85 KB
/
MessageBus.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#pragma once
#include <string>
#include <functional>
#include <map>
#include "Any.hpp"
#include "function_traits.hpp"
#include "NonCopyable.hpp"
using namespace std;
class MessageBus: NonCopyable
{
public:
//注册消息
template<typename F>
void Attach(F&& f, const string& strTopic="")
{
auto func = to_function(std::forward<F>(f));
Add(strTopic, std::move(func));
}
//发送消息
template<typename R>
void SendReq(const string& strTopic = "")
{
using function_type = std::function<R()>;
string strMsgType =strTopic+ typeid(function_type).name();
auto range = m_map.equal_range(strMsgType);
for (Iterater it = range.first; it != range.second; ++it)
{
auto f = it->second.AnyCast < function_type >();
f();
}
}
template<typename R, typename... Args>
void SendReq(Args&&... args, const string& strTopic = "")
{
using function_type = std::function<R(Args...)>;
string strMsgType =strTopic+ typeid(function_type).name();
auto range = m_map.equal_range(strMsgType);
for (Iterater it = range.first; it != range.second; ++it)
{
auto f = it->second.AnyCast < function_type >();
f(std::forward<Args>(args)...);
}
}
//移除某个主题, 需要主题和消息类型
template<typename R, typename... Args>
void Remove(const string& strTopic = "")
{
using function_type = std::function<R(Args...)>; //typename function_traits<void(CArgs)>::stl_function_type;
string strMsgType =strTopic +typeid(function_type).name();
int count = m_map.count(strMsgType);
auto range = m_map.equal_range(strMsgType);
m_map.erase(range.first, range.second);
}
private:
template<typename F>
void Add(const string& strTopic, F&& f)
{
string strMsgType = strTopic + typeid(F).name();
m_map.emplace(std::move(strMsgType), std::forward<F>(f));
}
private:
std::multimap<string, Any> m_map;
typedef std::multimap<string, Any>::iterator Iterater;
};