R-Type 0.1
Loading...
Searching...
No Matches
busEvents.hpp
1#pragma once
2
7#include <algorithm>
8#include <functional>
9#include <iostream>
10#include <string>
11#include <typeindex>
12#include <unordered_map>
13#include <vector>
14
20class busEvent {
21private:
22 std::unordered_map<std::type_index,
23 std::vector<std::function<void(const void *event)>>>
24 _handlers;
25
26public:
32 template <typename E>
33 void subscribe(std::function<void(const E &event)> func) {
34 auto it = _handlers.find(typeid(E));
35 if (it != _handlers.end()) {
36 it->second.push_back([fct = std::move(func)](const void *event) {
37 fct(*static_cast<const E *>(event));
38 });
39 return;
40 }
41 std::vector<std::function<void(const void *event)>> functionList;
42 functionList.push_back([fct = std::move(func)](const void *event) {
43 fct(*static_cast<const E *>(event));
44 });
45 _handlers.insert({typeid(E), functionList});
46 }
52 template <typename E> void publish(const E &event) {
53 auto it = _handlers.find(typeid(E));
54 if (it == _handlers.end()) {
55 return;
56 }
57 auto &handler = it->second;
58 for (const auto &h : handler) {
59 h(&event);
60 }
61 }
62};
63
Type indexed publish and subscribe event bus.
Definition busEvents.hpp:20
void subscribe(std::function< void(const E &event)> func)
Registers a handler for one event type.
Definition busEvents.hpp:33
void publish(const E &event)
Calls every handler registered for the event type.
Definition busEvents.hpp:52