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;   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值