codex
Loading...
Searching...
No Matches
event_dispatcher.hpp
Go to the documentation of this file.
1#ifndef CODEX_EVENT_DISPATCHER_EVENT_DISPATCHER_HPP
2#define CODEX_EVENT_DISPATCHER_EVENT_DISPATCHER_HPP
3
4#include <concepts>
5#include <cstdio>
6#include <functional>
7#include <vector>
8
9namespace codex {
10
12struct BaseEvent {};
14struct OnClick : BaseEvent { int button; };
16struct OnKey : BaseEvent { int key; };
17
19template<typename T> concept Event = std::derived_from<T, BaseEvent>;
21template<typename T, typename E>
22concept EventListener = Event<E> && std::invocable<T, E>;
23
24namespace detail {
25
27template<Event E> struct EventListenerVec
28 { protected: std::vector<std::function<void(E)>> v; };
29
30}
31
39template<Event ...Es>
41public:
43 template<Event E, EventListener<E> L>
44 void add_listener(L l) { this->vec<E>().emplace_back(std::move(l)); }
46 template<Event E> void trigger(E e) { for(auto &x: this->vec<E>()) x(e); }
47private:
49 template<Event E>
50 requires std::is_base_of_v<
52 decltype(auto) vec() { return (detail::EventListenerVec<E>::v); }
53};
54
55}
56
57#endif
A type-safe event listener/dispatcher.
Definition event_dispatcher.hpp:40
void add_listener(L l)
Adds a callback for a given event type.
Definition event_dispatcher.hpp:44
decltype(auto) vec()
Helper method to access the storage for a particular event type.
Definition event_dispatcher.hpp:52
void trigger(E e)
Invokes all listeners associated with the event type.
Definition event_dispatcher.hpp:46
Constrains a callable to an event type.
Definition event_dispatcher.hpp:22
Semi-arbitrary method to identify an event type.
Definition event_dispatcher.hpp:19
#define x
Definition gcc14.c:1
Definition rotate.hpp:6
Definition power.hpp:8
Definition soa.cpp:6
Base class tag to identify events.
Definition event_dispatcher.hpp:12
Sample button click event.
Definition event_dispatcher.hpp:14
int button
Definition event_dispatcher.hpp:14
Sample key press event.
Definition event_dispatcher.hpp:16
int key
Definition event_dispatcher.hpp:16
Storage base class for a given event type.
Definition event_dispatcher.hpp:28
std::vector< std::function< void(E)> > v
Definition event_dispatcher.hpp:28