-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventHandler.h
70 lines (58 loc) · 1.59 KB
/
eventHandler.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
#ifndef CHESS_EVENTHANDLER_H
#define CHESS_EVENTHANDLER_H
#include <vector>
#include <functional>
template <typename RetType>
class eventInvoke{
public:
std::vector<RetType> returns;
std::exception exception;
bool success;
void apply(const std::function<void(RetType)> &func){
for (RetType ret : returns) func(ret);
}
};
template<>
class eventInvoke<void>{
public:
std::exception exception;
bool success;
};
template <typename Func>
class eventHandler;
template <typename RetType, typename... Args>
class eventHandler<RetType(Args...)> {
typedef std::function<RetType(Args...)> function;
std::vector<function> functions;
public:
eventHandler()= default;
void subscribe(const function &func){
functions.push_back(func);
}
eventInvoke<RetType> invoke(Args... args){
if constexpr(!std::is_void_v<RetType>) {
std::vector<RetType> returns;
try {
for (const function &func: functions) returns.push_back(func(args...));
} catch (std::exception &e) {
return {{}, e, false};
}
return {returns, {}, true};
}else {
try {
for (const function &func: functions) func(args...);
} catch (std::exception &e) {
return {e, false};
}
return {{}, true};
}
}
eventHandler &operator+=(const function &func){
subscribe(func);
return *this;
}
eventInvoke<RetType> operator()(Args... args){
return invoke(args...);
}
};
#endif