4#include <unordered_map>
8#include "../_Core/logger.h"
25 template <
typename ...DataType>
28 Callback(std::shared_ptr<std::function<
void(DataType...)>> func) : func(func) {}
35 void evoke(DataType... args) { (*func)(args...); }
38 std::shared_ptr<std::function<void(DataType...)>> func;
49 using Map = std::unordered_map<int, std::unordered_map<Id, std::shared_ptr<ICallback>>>;
60 template <
typename Event>
63 template <
typename Event>
75 template <
typename Event,
typename ...DataType>
76 Id addListener(Event event, std::shared_ptr<std::function<
void(DataType...)>> callbackFunc) {
77 const Id id =
Id(++id_value());
90 template <
typename Event>
92 if (map.count((
int) event)) {
93 int removeCnt = map[(int) event].erase(
id);
94 if (!removeCnt)
SWARN(
"Trying to remove listener %d from event %d, but the event does not have this listener.",
id, event);
96 SWARN(
"Trying to remove a listener from event %d, but the event does not exist.", event);
107 template <
typename Event,
typename ...DataType>
108 void invoke(Event event, DataType... args) {
109 if (map.count((
int) event))
110 for (
auto& pp : map[(
int) event])
111 std::dynamic_pointer_cast<
Callback<DataType...>>(pp.second)->evoke(args...);
116 static auto id_value()
118 static uint64_t the_id;
A wrapper around a shared_ptr to a function.
Definition: eventmap.h:26
Callback(std::shared_ptr< std::function< void(DataType...)> > func)
Definition: eventmap.h:28
void evoke(DataType... args)
Call the function this stores.
Definition: eventmap.h:35
A mapping between events (which are ints under the hood) and callbacks.
Definition: eventmap.h:45
Map::iterator iterator
Definition: eventmap.h:51
iterator begin()
Definition: eventmap.h:57
iterator find(Event event)
Definition: eventmap.h:61
Map::const_iterator const_iterator
Definition: eventmap.h:52
const_iterator find(Event event) const
Definition: eventmap.h:64
Map::value_type value_type
Definition: eventmap.h:53
void removeListener(Event event, Id id)
Remove a listener from an event, by their id.
Definition: eventmap.h:91
Id
Definition: eventmap.h:47
const_iterator end() const
Definition: eventmap.h:56
void invoke(Event event, DataType... args)
Invoke an event. This calls all listeners attached to that event, with the specified parameters.
Definition: eventmap.h:108
Id addListener(Event event, std::shared_ptr< std::function< void(DataType...)> > callbackFunc)
Add a listener to a specific event.
Definition: eventmap.h:76
iterator end()
Definition: eventmap.h:58
const_iterator begin() const
Definition: eventmap.h:55
Generic callback used for events.
Definition: eventmap.h:15
virtual ~ICallback()=default
#define SWARN(message,...)
Log warn-level messages.
Definition: logger.h:77