Lodestone.Common
Loading...
Searching...
No Matches
Event.h
Go to the documentation of this file.
1
11#ifndef LODESTONE_EVENT_H
12#define LODESTONE_EVENT_H
13#include <functional>
14#include <cstdint>
15#include <limits>
16#include <format>
17#include <stdexcept>
18
21
23 using FunctionHandle = unsigned int;
24
25 template <typename... Args>
26 class Event {
27 public:
28 using Handler = std::function<void(Args...)>;
29
30 static constexpr FunctionHandle MAX_SUBSCRIBERS = std::numeric_limits<FunctionHandle>::max();
31
36
37 template <std::invocable<Args...> Func>
38 FunctionHandle subscribe(Func &&handler) {
39 if (this->m_nextId == MAX_SUBSCRIBERS) // how the fuck do you manage this
40 throw std::length_error(std::format("The maximum number of subscribers to this event has been reached ({}/{})", this->m_listeners.size(), MAX_SUBSCRIBERS));
41
42 this->m_listeners.push_back(Subscriber {
43 this->m_nextId,
44 std::forward<Func>(handler)
45 });
46
47 return this->m_nextId++;
48 }
49
51 return std::erase_if(this->m_listeners, [&id](const Subscriber &subscriber) {
52 return subscriber.id == id;
53 }) > 0;
54 }
55
56 void notify(Args... args) {
57 for (Subscriber listener : this->m_listeners) {
58 std::invoke(listener.handler, std::forward<Args>(args)...);
59 }
60 }
61
62 // I wanted it to be like C#'s events
63 template <std::invocable<Args...> Func>
64 FunctionHandle operator+=(Func &&handler) {
65 return this->subscribe(std::forward<Func>(handler));
66 }
67
68 bool operator-=(const FunctionHandle id) {
69 return this->unsubscribe(id);
70 }
71
72 protected:
73 std::vector<Subscriber> m_listeners;
74
76 };
77
78 template <typename... Args>
79 using CancellableEvent = Event<Cancellable &, Args...>;
80}
81
82#endif // LODESTONE_EVENT_H
Definition Event.h:26
std::function< void(Args...)> Handler
Definition Event.h:28
FunctionHandle operator+=(Func &&handler)
Definition Event.h:64
FunctionHandle subscribe(Func &&handler)
Definition Event.h:38
bool unsubscribe(FunctionHandle id)
Definition Event.h:50
void notify(Args... args)
Definition Event.h:56
bool operator-=(const FunctionHandle id)
Definition Event.h:68
std::vector< Subscriber > m_listeners
Definition Event.h:73
static constexpr FunctionHandle MAX_SUBSCRIBERS
Definition Event.h:30
Definition Cancellable.h:14
unsigned int FunctionHandle
Definition Event.h:23
Event< Cancellable &, Args... > CancellableEvent
Definition Event.h:79
Definition Cancellable.h:15
Handler handler
Definition Event.h:34
FunctionHandle id
Definition Event.h:33