1 #ifndef _ZTC_DELEGATE_H_
2 #define _ZTC_DELEGATE_H_
3
4 #include <vector>
5 #include <functional>
6
7 ///////////////////////////////////////////////
8 // C++ 使用 可变参数模板类, 来实现
9 // C#中的 委托
10 // Anchor: ztc
11 // Date : 2014-01-10
12 ///////////////////////////////////////////////
13
14 template<typename R, typename ...Args>
15 class Delegate {
16 public:
17 template<typename U>
18 Delegate& operator += (const U &func) {
19 funcList.push_back(std::function<R(Args...)>(func));
20 funcPointers.push_back((void*)&func);
21 return *this;
22 }
23
24 template<typename U>
25 Delegate& operator -= (const U &func) {
26 int i = -1;
27 for (auto iter = funcPointers.begin(); iter != funcPointers.end(); iter++) {
28 i++;
29 if (*iter == (void*)&func) {
30 funcPointers.erase(iter);
31 funcList.erase(funcList.begin() + i);
32 break;
33 }
34 }
35 return *this;
36 }
37
38 std::vector<R> operator()(Args...args) {
39 std::vector<R> ret;
40 for (auto f : funcList) {
41 ret.push_back(f(args...));
42 }
43 return ret;
44 }
45 private:
46 std::vector<std::function<R(Args...)>> funcList;
47 std::vector<void*> funcPointers;
48 };
49
50 template<typename ...Args>
51 class Delegate<void, Args...> {
52 public:
53 template<typename U>
54 Delegate& operator += (const U &func) {
55 std::cout << "注册方法 " << typeid(func).name() << std::endl;
56 funcList.push_back(std::function<void(Args...)>(func));
57 funcPointers.push_back((void*)&func);
58 return *this;
59 }
60
61 template<typename U>
62 Delegate& operator -= (const U &func) {
63 std::cout << "卸载方法 " << typeid(func).name() << std::endl;
64 int i = -1;
65 for (auto iter = funcPointers.begin(); iter != funcPointers.end(); iter++) {
66 i++;
67 if (*iter == (void*)&func) {
68 funcPointers.erase(iter);
69 funcList.erase(funcList.begin() + i);
70 break;
71 }
72 }
73 return *this;
74 }
75
76 void operator() (Args... args) {
77 for (auto f : funcList) {
78 f(args...);
79 }
80 }
81 private:
82 std::vector<std::function<void(Args...)>> funcList;
83 std::vector<void*> funcPointers;
84 };
85
86 #endif // _ZTC_DELEGATE_H_