Vanetza
 
Loading...
Searching...
No Matches
hook.hpp
1#ifndef HOOK_HPP_RNAM6XF4
2#define HOOK_HPP_RNAM6XF4
3
4#include <functional>
5#include <utility>
6
7namespace vanetza
8{
9
10/**
11 * Hook mechanism for realising extension points
12 */
13template<typename... Args>
14class Hook
15{
16public:
17 typedef std::function<void(Args...)> callback_type;
18
19 /**
20 * Assign a callback to hook, replaces previously assigned one
21 * \param cb A callable used as hook callback, e.g. lambda
22 */
23 void operator=(callback_type&& cb)
24 {
25 m_function = std::move(cb);
26 }
27
28 void operator=(const callback_type& cb)
29 {
30 m_function = cb;
31 }
32
33 /**
34 * Execute hook callback if assigned
35 * \param Args... various arguments passed to assigned callback
36 */
37 void operator()(Args... args)
38 {
39 if (m_function) {
40 // that's an arcane syntax, isn't it?
41 m_function(std::forward<Args>(args)...);
42 }
43 }
44
45 /**
46 * Reset previously assigned callback.
47 * No callback will be invoked when triggering hook after reset.
48 */
49 void reset()
50 {
51 m_function = nullptr;
52 }
53
54 /**
55 * \deprecated previous name of reset
56 */
57 void clear() { reset(); }
58
59private:
60 callback_type m_function;
61};
62
63/**
64 * Hook registry (non-callable view of a hook)
65 *
66 * Callbacks can be assigned to a hook via the corresponding registry,
67 * but the callback cannot be invoked through the registry.
68 */
69template<typename... Args>
71{
72public:
73 using hook_type = Hook<Args...>;
74 using callback_type = typename hook_type::callback_type;
75
76 HookRegistry(hook_type& hook) : m_hook(hook) {}
77
78 void operator=(callback_type&& cb)
79 {
80 m_hook = std::move(cb);
81 }
82
83 void operator=(const callback_type& cb)
84 {
85 m_hook = cb;
86 }
87
88 void reset()
89 {
90 m_hook.reset();
91 }
92
93private:
94 hook_type& m_hook;
95};
96
97} // namespace vanetza
98
99#endif /* HOOK_HPP_RNAM6XF4 */
100
void reset()
Definition: hook.hpp:49
void operator=(callback_type &&cb)
Definition: hook.hpp:23
void operator()(Args... args)
Definition: hook.hpp:37
void clear()
Definition: hook.hpp:57