-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallback.hpp
70 lines (63 loc) · 1.74 KB
/
callback.hpp
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 DHTSIM_CALLBACK_H
#define DHTSIM_CALLBACK_H
#include <functional>
namespace dhtsim {
template <typename SuccessParameter,
typename FailureParameter = SuccessParameter>
class CallbackSet {
public:
using SuccessFn = std::function<void(SuccessParameter)>;
using FailureFn = std::function<void(FailureParameter)>;
// Main constructors
CallbackSet() : successFns({}), failureFns({}) {}
CallbackSet(const std::vector<SuccessFn>& successFns,
const std::vector<FailureFn>& failureFns)
: successFns(successFns),
failureFns(failureFns) {};
CallbackSet(const SuccessFn& successFn,
const FailureFn& failureFn) {
this->successFns.push_back(successFn);
this->failureFns.push_back(failureFn);
}
// Static constructors
static CallbackSet onSuccess(SuccessFn fn) {
CallbackSet s;
s.successFns.push_back(fn);
return s;
}
static CallbackSet onFailure(FailureFn fn) {
CallbackSet s;
s.failureFns.push_back(fn);
return s;
}
void success(SuccessParameter m) const {
for (const auto& sf : this->successFns) {
sf(m);
}
}
void failure(FailureParameter m) const {
for (const auto& ff : this->failureFns) {
ff(m);
}
}
bool empty() const {
return this->successFns.empty() && this->failureFns.empty();
}
void operator+=(const CallbackSet& other) {
this->successFns.insert(this->successFns.end(),
other.successFns.begin(), other.successFns.end());
this->failureFns.insert(this->failureFns.end(),
other.failureFns.begin(), other.failureFns.end());
}
friend CallbackSet operator+(const CallbackSet& c1, const CallbackSet& c2) {
CallbackSet result;
result += c1;
result += c2;
return result;
}
private:
std::vector<SuccessFn> successFns;
std::vector<FailureFn> failureFns;
};
}
#endif