4#include <unordered_map>
14template<
typename EventBaseType>
22 template<
typename EventType,
typename Callback>
25 static_assert(std::is_base_of_v<EventBaseType, EventType>,
26 "EventType must inherit from EventBaseType");
27 static_assert(std::is_invocable_r_v<void, Callback, const EventType&>,
28 "Callback must be invocable with const EventType&");
30 std::unique_lock lock(
mutex_);
31 auto& subscribers =
subscribers_[std::type_index(
typeid(EventType))];
35 [cb = std::forward<Callback>(callback)](
const EventBaseType* event)
39 cb(*
static_cast<const EventType*
>(event));
41 catch (
const std::exception& e)
43 std::cerr <<
"Exception in event callback: " << e.what() << std::endl;
47 std::cerr <<
"Unknown exception in event callback" << std::endl;
55 template<
typename EventType>
56 void publish(
const EventType& event)
const
58 static_assert(std::is_base_of_v<EventBaseType, EventType>,
59 "EventType must inherit from EventBaseType");
61 std::shared_lock lock(
mutex_);
65 auto subscribersCopy = it->second;
68 for (
const auto& subscriber : subscribersCopy)
70 subscriber.callback(&event);
76 template<
typename EventType>
79 static_assert(std::is_base_of_v<EventBaseType, EventType>,
80 "EventType must inherit from EventBaseType");
82 std::unique_lock lock(
mutex_);
89 std::unique_lock lock(
mutex_);
93 std::remove_if(subscribers.begin(), subscribers.end(),
94 [
id](
const auto& subscriber) { return subscriber.id == id; }),
105 std::function<void(
const EventBaseType*)>
callback;
Definition EventBus.hpp:16
void publish(const EventType &event) const
Definition EventBus.hpp:56
std::shared_mutex mutex_
Definition EventBus.hpp:110
SubscriptionId nextSubscriptionId_
Definition EventBus.hpp:112
std::unordered_map< std::type_index, SubscriberList > subscribers_
Definition EventBus.hpp:111
size_t SubscriptionId
Definition EventBus.hpp:19
std::vector< Subscriber > SubscriberList
Definition EventBus.hpp:108
void unsubscribe(SubscriptionId id)
Definition EventBus.hpp:87
void unsubscribeAll()
Definition EventBus.hpp:77
SubscriptionId subscribe(Callback &&callback)
Definition EventBus.hpp:23
Definition EventBus.hpp:103
std::function< void(const EventBaseType *)> callback
Definition EventBus.hpp:105
SubscriptionId id
Definition EventBus.hpp:104