-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleCallBackWrapper.cpp
More file actions
58 lines (50 loc) · 1.31 KB
/
SimpleCallBackWrapper.cpp
File metadata and controls
58 lines (50 loc) · 1.31 KB
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
typedef std::function<void()> CallBackT;
template<typename T>
class SimpleCallBackWrapper
{
private:
T fun_;
CallBackT cb_;
void onStart() { cout << "start!" << endl; }
public:
SimpleCallBackWrapper(T&& fun, const CallBackT& cb):
fun_(fun), cb_(cb) { onStart(); }
SimpleCallBackWrapper(const T& fun, const CallBackT& cb):
fun_(fun), cb_(cb) { onStart(); }
template<typename... Args>
void operator()(Args&&... args)
{
fun_(std::forward<Args>(args)...);
cb_();
}
};
template<typename T>
SimpleCallBackWrapper<typename std::remove_reference<T>::type>
makeSimpleCallbackWrapper(T&& fun, const CallBackT& cb)
{
return SimpleCallBackWrapper<typename std::remove_reference<T>::type>
(std::forward<T>(fun), cb);
}
void onEnd()
{
cout << "End!" << endl;
}
void worker_thread(int num)
{
for (int i=0; i<5; ++i)
{
cout << "thread"<<num<<" is working ("<<(i+1)<<"/5)"<<endl;
}
}
int main()
{
std::thread t(makeSimpleCallbackWrapper(&worker_thread, &onEnd), 1);
t.join();
//start!
//thread1 is working (1/5)
//thread1 is working (2/5)
//thread1 is working (3/5)
//thread1 is working (4/5)
//thread1 is working (5/5)
//End!
}