/
Callback_test.cpp
159 lines (126 loc) · 2.35 KB
/
Callback_test.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#include "Callback.h"
#include <cassert>
void
test_construction()
{
Callback cb;
// Make sure default constructed tests as false. (similar to normal
// pointers.)
assert(cb == false);
// Make sure default constructed tests as equal to nullptr;
assert(cb == nullptr);
// Ensure copy construction.
Callback cb2 = cb;
// Ensure assignment.
cb2 = cb;
}
static int testVar = 0;
// Note: Need external linkage to use as template argument.
// use namespace {} instead of static.
namespace
{
void
testAdd(int x)
{
testVar += x;
}
void
testDiff(int x)
{
testVar -= x;
}
} // namespace
void
testFreeFunction()
{
// Create simple callback to a normal free function.
Callback cb = Callback::make<testAdd>();
// Try making a call. Check result.
testVar = 2;
cb(3);
assert(testVar == 5);
// Test copy constructor.
Callback cb2(cb);
testVar = 4;
cb2(3);
assert(testVar == 7);
// Test assign.
cb = Callback::make<testDiff>();
testVar = 4;
cb(3);
assert(testVar == 1);
}
struct TestObj
{
TestObj() : m_val(3) {}
int m_val;
void add(int x)
{
m_val += x;
}
};
void
adder(TestObj* o, int val)
{
o->m_val += val;
}
void
testFreeFunctionWithPtr()
{
TestObj o;
// Create simple callback to a normal free function.
Callback cb = Callback::make<TestObj*, adder>(&o);
o.m_val = 6;
cb(3);
assert(o.m_val == 9);
o.m_val = 3;
cb(9);
assert(o.m_val == 12);
}
void
testMemberFunction()
{
TestObj o;
// Create member function callback.
Callback cb = Callback::make<TestObj, &TestObj::add>(o);
o.m_val = 6;
cb(3);
assert(o.m_val == 9);
o.m_val = 3;
cb(9);
assert(o.m_val);
// Try MACRO construction.
Callback cb2 = MAKE_MEMBER_CB(TestObj, TestObj::add, o);
o.m_val = 6;
cb2(3);
assert(o.m_val == 9);
o.m_val = 3;
cb2(9);
assert(o.m_val == 12);
}
struct Functor
{
void operator()(int x)
{
val += x;
}
int val;
};
void
testFunctorFunction()
{
Functor fkn;
// Create simple callback to a normal free function.
Callback cb = Callback::make(fkn);
fkn.val = 3;
cb(4);
assert(fkn.val == 7);
}
int
main()
{
test_construction();
testFreeFunction();
testFreeFunctionWithPtr();
testMemberFunction();
}