-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent_bus.hpp
More file actions
63 lines (51 loc) · 1.48 KB
/
event_bus.hpp
File metadata and controls
63 lines (51 loc) · 1.48 KB
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
#pragma once
#include <unordered_map>
#include <vector>
#include <typeindex>
#include <functional>
class EventBus
{
public:
template <typename EventType>
void Subscribe(const std::function<void(const EventType& event)>& callback, void* subscriber)
{
Subscription s = {};
s.handle = reinterpret_cast<uintptr_t>(subscriber);
s.callback = [callback](const void* event) {
callback(*static_cast<const EventType*>(event));
};
m_subscriptions[typeid(EventType)].emplace_back(s);
}
template <typename EventType>
void Publish(const EventType& event)
{
std::type_index typeIdx = typeid(EventType);
auto it = m_subscriptions.find(typeIdx);
if (it == m_subscriptions.end()) return;
for (Subscription& subscription : it->second)
{
subscription.callback(&event);
}
}
template <typename EventType>
void Unsubscribe(void* self)
{
uintptr_t subscriberId = reinterpret_cast<uintptr_t>(self);
std::type_index typeIdx = typeid(EventType);
auto it = m_subscriptions.find(typeIdx);
if (it == m_subscriptions.end()) return;
std::vector<Subscription>& subscriptions = it->second;
subscriptions.erase(
std::remove_if(subscriptions.begin(),
subscriptions.end(),
[this, subscriberId](const Subscription& data) { return data.handle == subscriberId; }),
subscriptions.end());
}
private:
struct Subscription
{
uintptr_t handle;
std::function<void(const void*)> callback;
};
std::unordered_map<std::type_index, std::vector<Subscription>> m_subscriptions;
};