-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsignal.h
90 lines (72 loc) · 2.09 KB
/
signal.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#ifndef JWUTIL_SIGNAL_H
#define JWUTIL_SIGNAL_H
#include <assert.h>
#include <type_traits>
#include <vector>
#include <algorithm>
#include "methodcallback.h"
namespace jw_util
{
template <typename... ArgTypes>
class SignalEmitter {
public:
class Listener {
public:
Listener(SignalEmitter &signal, const jw_util::MethodCallback<ArgTypes...> &callback_arg)
: signal(signal)
, callback(callback_arg)
{
enable();
}
~Listener() {
disable();
}
void enable() {
signal.add(callback);
}
void disable() {
signal.remove(callback);
}
private:
SignalEmitter &signal;
jw_util::MethodCallback<ArgTypes...> callback;
};
SignalEmitter() {}
// Disable moving
SignalEmitter(SignalEmitter&&) = delete;
SignalEmitter(const SignalEmitter&) = delete;
SignalEmitter& operator=(const SignalEmitter&) = delete;
~SignalEmitter() {
assert(callbacks.empty());
}
protected:
void trigger(ArgTypes... args) {
typename std::vector<jw_util::MethodCallback<ArgTypes...>>::const_iterator i
= callbacks.cbegin();
while (i != callbacks.cend()) {
i->call(std::forward<ArgTypes>(args)...);
i++;
}
}
private:
void add(const jw_util::MethodCallback<ArgTypes...> &callback) {
callbacks.push_back(callback);
}
void remove(const jw_util::MethodCallback<ArgTypes...> &callback) {
typename std::vector<jw_util::MethodCallback<ArgTypes...>>::reverse_iterator found
= std::find(callbacks.rbegin(), callbacks.rend(), callback);
assert(found != callbacks.rend());
*found = callbacks.back();
callbacks.pop_back();
}
std::vector<jw_util::MethodCallback<ArgTypes...>> callbacks;
};
template <typename... ArgTypes>
class Signal : public SignalEmitter<ArgTypes...> {
public:
void trigger(ArgTypes... args) {
SignalEmitter<ArgTypes...>::trigger(std::forward<ArgTypes>(args)...);
}
};
}
#endif // JWUTIL_SIGNAL_H