Loading...
Searching...
No Matches
Hookable.h
Go to the documentation of this file.
1// Copyright (c) 2025 Dave R. Smith.
2// Malena Framework — Licensed under PolyForm Noncommercial 1.0.0; commercial use requires a paid license. See LICENSE.
3
4#ifndef MALENA_HOOKABLE_H
5#define MALENA_HOOKABLE_H
6
9#include <memory>
10#include <type_traits>
11
12namespace ml
13{
14 namespace detail
15 {
16 template<typename F> struct cb_arg;
17 template<typename C, typename R, typename A>
18 struct cb_arg<R(C::*)(A) const> { using type = std::decay_t<A>; };
19 template<typename C, typename R, typename A>
20 struct cb_arg<R(C::*)(A)> { using type = std::decay_t<A>; };
21 }
22
23 template<typename F>
24 using cb_arg_t = typename detail::cb_arg<decltype(&std::decay_t<F>::operator())>::type;
25
43 {
44 virtual ~Hookable() = default;
45
46 template<typename Enum>
47 void sendHook(Enum hook) {
48 sendMessage<Hookable*>(hook, this);
49 }
50
51 template<typename Enum, typename Callback>
52 void onHook(Enum hook, Callback&& cb) {
53 using T = cb_arg_t<Callback>;
55 [cb = std::forward<Callback>(cb)](Hookable* w) {
56 if constexpr (std::is_same_v<T, Hookable>) {
57 cb(*w);
58 } else {
59 if (auto* p = dynamic_cast<T*>(w))
60 cb(*p);
61 }
62 }
63 );
64 }
65 };
66
67} // namespace ml
68
69#endif // MALENA_HOOKABLE_H
Trait that adds typed, enum-keyed message sending and receiving to any class.
Definition Messenger.h:68
void sendMessage(Enum event, const DataType &data)
Publish a typed message to all current subscribers.
void onMessage(Enum event, std::function< void(const DataType &)> callback)
Register a callback to receive a typed message.
std::function< void()> Callback
Callback type for no-argument event handlers.
Definition Callback.h:49
#define MALENA_API
Definition Component.h:22
typename detail::cb_arg< decltype(&std::decay_t< F >::operator())>::type cb_arg_t
Definition Hookable.h:24
Trait that layers a hook system on top of ml::Messenger.
Definition Hookable.h:43
void sendHook(Enum hook)
Definition Hookable.h:47
virtual ~Hookable()=default
void onHook(Enum hook, Callback &&cb)
Definition Hookable.h:52