zoukankan      html  css  js  c++  java
  • C++实现委托机制(二)

    1.引言:

                 上一篇文章已经介绍了如何构建一个无参数无返回值的函数指针的委托,这篇文章将对上一文章所述委托进行扩展,使得可以注册任意函数指针,不过再讲篇内容之前先要介绍一下实现这个功能所需要了解的C++11的一个新特性———可变参数模板


    2.可变参数模板:

                 template(模板)是源于将类型和实现(算法)分离开的思想,为了让写好的算法适用于更多类型使得出现了模板,模板使得参数类别任意化,如果再加上“参数个数的任意化”,那么在参数方面的设计手段就基本上齐备了,有了variadic template 显然可以让设计出来的函数或是类有更大的复用性。因为有很多处理都是与“处理对象的个数”关系不大的,比如说打屏(printf),比如说比较大小(max,min),比如函数绑定子(bind,function要对应各种可能的函数就要能“任意”参数个数和类型)。如果不能对应任意个参数,那么就总会有人无法重用已有的实现,而不得不再重复地写一个自己需要的处理,而共通库的实现者为了尽可能地让自己写的类(函数)能复用在更多的场景,也不得不重复地写很多的代码或是用诡异的技巧,宏之类的去实现有限个“任意参数”的对应。
                 所以在C++11中引入了这个新语法,下面我们先看一个例子,了解基本的语法:

    1. template<typename ... Params> class MyClass;  
    2.    
    3. MyClass<int, string> a;   
                
     在上面这个例子我们可以看到,在定义和申明中用 typename...  表示一个参数包,这样我们使用的时候,传入一个<int,string>那么int,string就会被打包入Params中。恩,你可以吧这个参数包看做一个参数的结构体,并且这个结构体的大小是动态的,并且是匿名的。恩,也就是说你无法使用Params[0]这样的语法去随机调用某个类型。听到这里,觉得是匿名的那应该怎么使用呢?答案是递归展开!!!我们先来看一个函数的例子,假如我想写一个Max函数求传入所有参数的最大值,这个参数支持(int,double,float),返回值为double.那么函数原型你觉得大概可能是这样子的:

    1. template<typename ...Params>  
    2. double Max(Params... _params)  
    3. {  
    4.     double Maxnum;  
    5.   
    6.     //求解过程  
    7.   
    8.     return Maxnum;  
    9. }  
        
         但是这样写你会发现你无法获取到任何传入参数的类型和值。恩,所以我们来看下如何使用递归来获得每个参数的类型和值。

    1. template<typename Head,typename ...Tail>  
    2. double Max(Head first,Tail... rest)  
    3. {  
    4.     double Maxnum;  
    5.     Maxnum = Max(rest...);  
    6.     if (Maxnum < first)  
    7.         Maxnum = first;  
    8.     return Maxnum;  
    9. }  

         可以看到,我将函数参数分离了一个出来作为Head,这样我就可以每次处理一个变量,使用递归下降,每次递归减少一个参数。注意:上面的rest...表示参数展开,也就是说将这个参数包展开然后当做参数传进去。但是这样做还是不够的,大家都知道递归需要一个出口。所以说我们需要一个重载版本(因为模板函数不能偏特化)。

    1. template<typename Head>  
    2. double Max(Head first)  
    3. {  
    4.     return first;  
    5. }  

         这样就有了一个递归出口了。好,我们结合以上的代码写成一个完整的程序,看下如何使用的:

    1. #include<iostream>  
    2. using namespace std;  
    3.   
    4. template<typename Head, typename ...Tail>  
    5. double Max(Head first, Tail... rest)  
    6. {  
    7.     double Maxnum=0;  
    8.     Maxnum = Max(rest...);  
    9.     if (Maxnum < first)  
    10.         Maxnum = first;  
    11.     return Maxnum;  
    12. }  
    13. template<typename Head>  
    14. double Max(Head first)  
    15. {  
    16.     return first;  
    17. }  
    18.   
    19. int main()  
    20. {  
    21.     cout << Max(1, 3, 3.4, 5.1, 1.5);  
    22. }  

         输出结果是: 5.1,同样的,模板类是通过私有继承来实现递归的。
         
    1. template<typename Head, typename... Tail>  
    2. class tuple<Head, Tail...> : private tuple<Tail...>{  
    3.     Head head;  
    4. public:  
    5.     /* implementation */  
    6. };  
    7. template<typename Head>  
    8. class tuple<Head> {  
    9.     /* one-tuple implementation */  
    10. };  

         以上可变参数的基本内容就讲完了,如果还有不懂的可以自行百度

    3.任意参数个数、返回值任意的函数指针委托

         同样的,我们还是先对接口进行修改,因为函数指针再不是void(*)(void)所以,接口也需要是一个模板类,而且还需要是一个可变参数模板。

    1. template<typename ReturnType, typename ...ParamType>  
    2. class IDelegate  
    3. {  
    4. public:  
    5.     IDelegate(){}  
    6.     virtual ~IDelegate(){}  
    7.     virtual bool isType(const std::type_info& _type) = 0;  
    8.     virtual ReturnType invoke(ParamType ... params) = 0;  
    9.     virtual bool compare(IDelegate<ReturnType, ParamType...> *_delegate) const = 0;  
    10. };  

         这样,这个接口的invoke函数将会是根据你的函数类型来动态生成对应的模板了。
         同样的,我们把剩下三个类按照如此进行改造:
    1. //StaticDelegate 普通函数的委托  
    2.   
    3. template<typename ReturnType, typename ...ParamType>  
    4. class CStaticDelegate :  
    5.     public IDelegate<ReturnType, ParamType...>  
    6. {  
    7. public:  
    8.   
    9.     typedef  ReturnType(*Func)(ParamType...);  
    10.   
    11.     CStaticDelegate(Func _func) : mFunc(_func) { }  
    12.   
    13.     virtual bool isType(const std::type_info& _type) { return typeid(CStaticDelegate<ReturnType, ParamType...>) == _type; }  
    14.   
    15.     virtual ReturnType invoke(ParamType ... params) { return mFunc(params...); }  
    16.   
    17.     virtual bool compare(IDelegate<ReturnType, ParamType ...> *_delegate)const  
    18.     {  
    19.         if (0 == _delegate || !_delegate->isType(typeid(CStaticDelegate<ReturnType, ParamType ...>))) return false;  
    20.         CStaticDelegate<ReturnType, ParamType ...> * cast = static_cast<CStaticDelegate<ReturnType, ParamType ...>*>(_delegate);  
    21.         return cast->mFunc == mFunc;  
    22.     }  
    23.   
    24.     virtual ~CStaticDelegate(){}  
    25. private:  
    26.     Func mFunc;  
    27. };  
    28.   
    29. //成员函数委托  
    30. template<typename T, typename ReturnType, typename ...ParamType>  
    31. class CMethodDelegate :  
    32.     public IDelegate<ReturnType, ParamType...>  
    33. {  
    34. public:  
    35.     typedef ReturnType(T::*Method)(ParamType...);  
    36.   
    37.     CMethodDelegate(T * _object, Method _method) : mObject(_object), mMethod(_method) { }  
    38.   
    39.     virtual bool isType(const std::type_info& _type) { return typeid(CMethodDelegate<T, ReturnType, ParamType...>) == _type; }  
    40.   
    41.     virtual ReturnType invoke(ParamType...params)  
    42.     {  
    43.         (mObject->*mMethod)(params...);  
    44.     }  
    45.   
    46.     virtual bool compare(IDelegate<ReturnType, ParamType...> *_delegate) const  
    47.     {  
    48.         if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate<ReturnType, ParamType...>))) return false;  
    49.         CMethodDelegate<ReturnType, ParamType...>* cast = static_cast<CMethodDelegate<ReturnType, ParamType...>*>(_delegate);  
    50.         return cast->mObject == mObject && cast->mMethod == mMethod;  
    51.     }  
    52.   
    53.     CMethodDelegate(){}  
    54.     virtual ~CMethodDelegate(){}  
    55. private:  
    56.     T * mObject;  
    57.     Method mMethod;  
    58. };  
    59.   
    60. //多播委托  
    61. template<typename ReturnType, typename ...ParamType>  
    62. class CMultiDelegate  
    63. {  
    64.       
    65. public:  
    66.       
    67.     typedef std::list<IDelegate<ReturnType, ParamType...>*> ListDelegate;  
    68.     typedef typename ListDelegate::iterator ListDelegateIterator;  
    69.     typedef typename ListDelegate::const_iterator ConstListDelegateIterator;  
    70.   
    71.     CMultiDelegate() { }  
    72.     ~CMultiDelegate() { clear(); }  
    73.   
    74.     bool empty() const  
    75.     {  
    76.         for (ConstListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)  
    77.         {  
    78.             if (*iter) return false;  
    79.         }  
    80.         return true;  
    81.     }  
    82.   
    83.     void clear()  
    84.     {  
    85.         for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)  
    86.         {  
    87.             if (*iter)  
    88.             {  
    89.                 delete (*iter);  
    90.                 (*iter) = nullptr;  
    91.             }  
    92.         }  
    93.     }  
    94.   
    95.   
    96.     CMultiDelegate<ReturnType, ParamType...>& operator+=(IDelegate<ReturnType, ParamType...>* _delegate)  
    97.     {  
    98.         for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)  
    99.         {  
    100.             if ((*iter) && (*iter)->compare(_delegate))  
    101.             {  
    102.                 delete _delegate;  
    103.                 return *this;  
    104.             }  
    105.         }  
    106.         mListDelegates.push_back(_delegate);  
    107.         return *this;  
    108.     }  
    109.   
    110.     CMultiDelegate<ReturnType, ParamType...>& operator-=(IDelegate<ReturnType, ParamType...>* _delegate)  
    111.     {  
    112.         for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)  
    113.         {  
    114.             if ((*iter) && (*iter)->compare(_delegate))  
    115.             {  
    116.                 if ((*iter) != _delegate) delete (*iter);       //避免同一个地址被delete两次  
    117.                 (*iter) = 0;  
    118.                 break;  
    119.             }  
    120.         }  
    121.         delete _delegate;  
    122.         return *this;  
    123.     }  
    124.   
    125.     std::vector<ReturnType> operator()(ParamType... params)  
    126.     {  
    127.         ListDelegateIterator iter = mListDelegates.begin();  
    128.         std::vector<ReturnType> _Results;  
    129.         while (iter != mListDelegates.end())  
    130.         {  
    131.             if (0 == (*iter))  
    132.             {  
    133.                 iter = mListDelegates.erase(iter);  
    134.             }  
    135.             else  
    136.             {  
    137.                 _Results.push_back((*iter)->invoke(params...));  
    138.                 ++iter;  
    139.             }  
    140.         }  
    141.         return _Results;  
    142.     }  
    143. private:  
    144.     CMultiDelegate<ReturnType, ParamType...>(const CMultiDelegate& _event);  
    145.     CMultiDelegate<ReturnType, ParamType...>& operator=(const CMultiDelegate& _event);  
    146.   
    147. private:  
    148.     ListDelegate mListDelegates;  
    149. };  


         但是这样写你会发现你在newDelegate里面对于传来的函数指针进行new CStaticDelegate或者new CMethodDelegate的时候需要制定函数返回值、参数的个数和类型,这显然不满足动态类型演化。这时候我们想,能不能给定一个函数指针,让代码自动去识别这个函数的返回值和参数呢?答案是可以的,我们只需要对上面的CStaticDelegate和CMethodDelegate特化一个版本即可。
         这里使用了一个小技巧:通过函数指针去得到函数返回值、参数个数类型。详情可以看看这里:http://bbs.csdn.net/topics/390652170?page=1
         这里我就直接贴我写好的代码:
     
     
    1. //普通函数的委托特化版本  
    2. template<typename ReturnType, typename ...ParamType>  
    3. class CStaticDelegate<ReturnType(*)(ParamType ...)> :  
    4.     public IDelegate<ReturnType, ParamType ...>  
    5. {  
    6. public:  
    7.   
    8.     //定义 Func 为 void (void) 函数类型指针。  
    9.     typedef  ReturnType(*Func)(ParamType...);  
    10.   
    11.     CStaticDelegate(Func _func) : mFunc(_func) { }  
    12.   
    13.     virtual bool isType(const std::type_info& _type) { return typeid(CStaticDelegate<ReturnType(*)(ParamType ...)>) == _type; }  
    14.   
    15.     virtual ReturnType invoke(ParamType ... params) { return mFunc(params...); }  
    16.   
    17.     virtual bool compare(IDelegate<ReturnType, ParamType ...> *_delegate)const  
    18.     {  
    19.         if (0 == _delegate || !_delegate->isType(typeid(CStaticDelegate<ReturnType(*)(ParamType ...)>))) return false;  
    20.         CStaticDelegate<ReturnType(*)(ParamType ...)> * cast = static_cast<CStaticDelegate<ReturnType(*)(ParamType ...)>*>(_delegate);  
    21.         return cast->mFunc == mFunc;  
    22.     }  
    23.   
    24.     virtual ~CStaticDelegate(){}  
    25. private:  
    26.     Func mFunc;  
    27. };  
    28.   
    29. //成员函数委托特化  
    30. template<typename T, typename ReturnType, typename ...ParamType>  
    31. class CMethodDelegate<T,ReturnType (T:: *)(ParamType...)> :  
    32.     public IDelegate<ReturnType, ParamType...>  
    33. {  
    34. public:  
    35.     typedef ReturnType(T::*Method)(ParamType...);  
    36.   
    37.     CMethodDelegate(T * _object, Method _method) : mObject(_object), mMethod(_method) { }  
    38.   
    39.     virtual bool isType(const std::type_info& _type) { return typeid(CMethodDelegate<T,ReturnType(T:: *)(ParamType...)>) == _type; }  
    40.   
    41.     virtual ReturnType invoke(ParamType...params)  
    42.     {  
    43.         return (mObject->*mMethod)(params...);  
    44.     }  
    45.   
    46.     virtual bool compare(IDelegate<ReturnType, ParamType...> *_delegate) const  
    47.     {  
    48.         if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate<T, ReturnType(T:: *)(ParamType...)>))) return false;  
    49.         CMethodDelegate<T, ReturnType(T:: *)(ParamType...)>* cast = static_cast<CMethodDelegate<T, ReturnType(T:: *)(ParamType...)>*>(_delegate);  
    50.         return cast->mObject == mObject && cast->mMethod == mMethod;  
    51.     }  
    52.   
    53.     CMethodDelegate(){}  
    54.     virtual ~CMethodDelegate(){}  
    55. private:  
    56.     T * mObject;  
    57.     Method mMethod;  
    58. };  

         这样我生成的时候只需要new CStaticDelegate<decltype(Func)>(Func),而特化版本的可以自动识别这个Func的返回值、参数个数和类型。
         最后我给出newDelegate的代码:

    1. template< typename T>  
    2. CStaticDelegate<T>* newDelegate(T func)  
    3. {  
    4.     return new CStaticDelegate<T>(func);  
    5. }  
    6. template< typename T,typename F>  
    7. CMethodDelegate<T,F>* newDelegate(T * _object, F func)  
    8. {  
    9.     return new CMethodDelegate<T, F>(_object, func);  
    10. }  

         写到这里基本上可变参数的委托就完成了,不过还需要注意一点就是void无返回值类型多播委托需要特殊处理。所以我们还需要一个多播委托对于ReturnType为void这个情况的特化。

    1. template< typename ...ParamType>  
    2. class CMultiDelegate<void, ParamType...>  
    3. {  
    4.   
    5. public:  
    6.   
    7.     typedef std::list<IDelegate<void, ParamType...>*> ListDelegate;  
    8.     typedef typename ListDelegate::iterator ListDelegateIterator;  
    9.     typedef typename ListDelegate::const_iterator ConstListDelegateIterator;  
    10.   
    11.     CMultiDelegate() { }  
    12.     ~CMultiDelegate() { clear(); }  
    13.   
    14.     bool empty() const  
    15.     {  
    16.         for (ConstListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)  
    17.         {  
    18.             if (*iter) return false;  
    19.         }  
    20.         return true;  
    21.     }  
    22.   
    23.     void clear()  
    24.     {  
    25.         for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)  
    26.         {  
    27.             if (*iter)  
    28.             {  
    29.                 delete (*iter);  
    30.                 (*iter) = nullptr;  
    31.             }  
    32.         }  
    33.     }  
    34.   
    35.     CMultiDelegate<void, ParamType...>& operator+=(IDelegate<void, ParamType...>* _delegate)  
    36.     {  
    37.         for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)  
    38.         {  
    39.             if ((*iter) && (*iter)->compare(_delegate))  
    40.             {  
    41.                 delete _delegate;  
    42.                 return *this;  
    43.             }  
    44.         }  
    45.         mListDelegates.push_back(_delegate);  
    46.         return *this;  
    47.     }  
    48.   
    49.     CMultiDelegate<void, ParamType...>& operator-=(IDelegate<void, ParamType...>* _delegate)  
    50.     {  
    51.         for (ListDelegateIterator iter = mListDelegates.begin(); iter != mListDelegates.end(); ++iter)  
    52.         {  
    53.             if ((*iter) && (*iter)->compare(_delegate))  
    54.             {  
    55.                 if ((*iter) != _delegate) delete (*iter);       //避免同一个地址被delete两次  
    56.                 (*iter) = 0;  
    57.                 break;  
    58.             }  
    59.         }  
    60.         delete _delegate;  
    61.         return *this;  
    62.     }  
    63.   
    64.     void operator()(ParamType... params)  
    65.     {  
    66.         ListDelegateIterator iter = mListDelegates.begin();  
    67.         while (iter != mListDelegates.end())  
    68.         {  
    69.             if (0 == (*iter))  
    70.             {  
    71.                 iter = mListDelegates.erase(iter);  
    72.             }  
    73.             else  
    74.             {  
    75.                 (*iter)->invoke(params...);  
    76.                 ++iter;  
    77.             }  
    78.         }  
    79.     }  
    80. private:  
    81.     CMultiDelegate<void, ParamType...>(const CMultiDelegate& _event);  
    82.     CMultiDelegate<void, ParamType...>& operator=(const CMultiDelegate& _event);  
    83.   
    84. private:  
    85.     ListDelegate mListDelegates;  
    86. };  


         所有代码都已经贴出来了,我把这些模板全部放到了MyDelegate.h头文件中。下面给一个使用的例子:
      

         

      1. #include "MyDelegate.h"    
      2. using namespace Delegate;    
      3.     
      4. void NormalFunc(int a)    
      5. {    
      6.     printf("这里是普通函数 :%d ", a);    
      7. }    
      8.     
      9. class A    
      10. {    
      11. public:    
      12.     static void StaticFunc(int a)    
      13.     {    
      14.         printf("这里是成员静态函数 : %d ", a);    
      15.     }    
      16.     void MemberFunc(int a)    
      17.     {    
      18.         printf("这里是成员非静态函数 : %d ", a);    
      19.     }    
      20. };    
      21. int _tmain(int argc, _TCHAR* argv[])    
      22. {    
      23.     //首先创建了一个返回值为 void ,参数为int 的一个委托。    
      24.     CMultiDelegate<void, int> e;    
      25.     
      26.     //将三个函数注册到该委托中    
      27.     e += newDelegate(NormalFunc);    
      28.     e += newDelegate(A::StaticFunc);    
      29.     e += newDelegate(&A(), &A::MemberFunc);    
      30.     
      31.     //调用    
      32.     e(1);    
      33.     
      34.     return 0;    
      35. } <strong> </strong> 
  • 相关阅读:
    【bzoj2733】[HNOI2012]永无乡 Treap启发式合并
    【bzoj1465/bzoj1045】糖果传递 数论
    【bzoj2768/bzoj1934】[JLOI2010]冠军调查/[Shoi2007]Vote 善意的投票 最小割
    【bzoj4003】[JLOI2015]城池攻占 可并堆
    【bzoj3011】[Usaco2012 Dec]Running Away From the Barn 可并堆
    【bzoj2809】[Apio2012]dispatching 贪心+可并堆
    【bzoj1455】罗马游戏 可并堆+并查集
    DOM的的概述
    wpf多程序集之间共享资源字典--CLR名称空间未定义云云
    WPF的Presenter(ContentPresenter)
  • 原文地址:https://www.cnblogs.com/zhoug2020/p/6591405.html
Copyright © 2011-2022 走看看