C++中用模板函数指针实现委托
一个简单的 “成员模版函数指针” 的实现,看看C++是如何优雅的实现委托的:
1 #include "stdafx.h"
2 #include <iostream>
3 using namespace std;
4
5 template<typename T>
6 class A
7 {
8 private:
9 typedef int (T::*delegateFun)(int);
10 T *_This;
11 delegateFun _deleGate;
12
13 public:
14 // This被代理的对象,delegateFun被代理的方法
15 // A(T *This, int (T::*delegateFun)(int))
16 // {
17 // _This = This;
18 // _deleGate = delegateFun;
19 // }
20
21 A(T *This, delegateFun pFun)
22 {
23 _This = This;
24 _deleGate = pFun;
25 }
26
27 // 被代理的函数
28 int execue(int c)
29 {
30 return (_This->*_deleGate)(c);
31 }
32 };
33
34 class B
35 {
36 public:
37 int FunA(int a)
38 {
39 return a + 10;
40 }
41
42 int FunB(int a)
43 {
44 return a - 10;
45 }
46 };
47
48 int main(int argc, char* argv[])
49 {
50 B *objB = new B();
51 A<B> delegateObj1(objB, (&B::FunA));
52 A<B> delegateObj2(objB, (&B::FunB));
53
54 cout<<delegateObj1.execue(10)<<endl;
55 cout<<delegateObj2.execue(20)<<endl;
56
57 return 0;
58 }
59
2 #include <iostream>
3 using namespace std;
4
5 template<typename T>
6 class A
7 {
8 private:
9 typedef int (T::*delegateFun)(int);
10 T *_This;
11 delegateFun _deleGate;
12
13 public:
14 // This被代理的对象,delegateFun被代理的方法
15 // A(T *This, int (T::*delegateFun)(int))
16 // {
17 // _This = This;
18 // _deleGate = delegateFun;
19 // }
20
21 A(T *This, delegateFun pFun)
22 {
23 _This = This;
24 _deleGate = pFun;
25 }
26
27 // 被代理的函数
28 int execue(int c)
29 {
30 return (_This->*_deleGate)(c);
31 }
32 };
33
34 class B
35 {
36 public:
37 int FunA(int a)
38 {
39 return a + 10;
40 }
41
42 int FunB(int a)
43 {
44 return a - 10;
45 }
46 };
47
48 int main(int argc, char* argv[])
49 {
50 B *objB = new B();
51 A<B> delegateObj1(objB, (&B::FunA));
52 A<B> delegateObj2(objB, (&B::FunB));
53
54 cout<<delegateObj1.execue(10)<<endl;
55 cout<<delegateObj2.execue(20)<<endl;
56
57 return 0;
58 }
59
浙公网安备 33010602011771号