转载 C++实现的委托机制

转载 C++实现的委托机制

1.引言

下面的委托实现使用的MyGUI里面的委托实现,MyGUI是一款强大的GUI库,想理解更多的MyGUI信息,猛击这里http://mygui.info/ 

最终的代码可以在这里下载:http://download.csdn.net/detail/gouki04/3641328  我们的目标是要实现一个跟.NET几乎完全一样的委托,使用简单,支持多播,可以添加删除委托。同时支持C++的普通函数、模板函数、类成员函数,类的静态成员函数,并且支持多态。使用方式如下:

 

  1. // 普通函数  
  2. void normalFunc(){ cout << "func1" << endl; }  
  3. class Base  
  4. {  
  5. public:  
  6. // 类成员函数  
  7. void classFunc(){ cout << "Base func1" << endl; }  
  8. };  
  9. int main()  
  10. {  
  11. Base b;  
  12. CMultiDelegate myDelegate;  
  13. myDelegate += newDelegate(normalFunc);  
  14. myDelegate += newDelegate(&b, &Base::classFunc);  
  15. myDelegate(); // 此时会调用normalFunc和classFunc  
  16. myDelegate -= newDelegate(&b, &Base::classFunc);  
  17. myDelegate(); // 此时会调用normalFunc  
  18. return 0;  
  19. }  

 

 

2.实现无参函数委托

要实现委托,首先要解决的是封装C++中的函数指针。因为在C++中,普通函数指针和类成员函数指针是完全不一样的。如下例子

 

  1. class CMyClass  
  2. {  
  3. public:  
  4.     void func(int);  
  5. };  
  6. // 定义一个指向CMyClass类型,参数列表为(int),返回值为void的函数指针  
  7. typedef void (CMyClass::*ClassMethod) (int); // 注意定义时使用了特殊的运算符::*  

 

那么此函数指针只能指向CMyClass类型的成员函数,不能指向其他类或者普通函数

类成员函数指针不能直接调用,要通过一个类实例来调用,如下

 

  1. CMyClass *object = new CMyClass;  
  2. ClassMethod method = CMyClass::func;  
  3. (object->*method)(5); // 注意调用时使用了特殊运算符->*  

 

那么如何封装呢?我们先来定义下接口吧

(为了简单起见,下面的实现都是以无参函数为例,后续会讲到如何支持任意参数)

 

  1. class IDelegate  
  2. {  
  3. public:  
  4.     virtual ~IDelegate() { }  
  5.     virtual bool isType(const std::type_info& _type) = 0;  
  6.     virtual void invoke() = 0;  
  7.     virtual bool compare(IDelegate *_delegate) const = 0;  
  8. };  

 

IDelegate类的接口很少,也很简单,必要接口只有一个,就是invoke,用于触发函数

但为了可以方便管理,使用了isType和compare函数来进行相等判断。

下面是封装的普通函数指针

 

 

  1. class CStaticDelegate : public IDelegate  
  2. {  
  3. public:  
  4.     typedef void (*Func)();  
  5.     CStaticDelegate(Func _func) : mFunc(_func) { }  
  6.     virtual bool isType( const std::type_info& _type) { return typeid(CStaticDelegate) == _type; }  
  7.     virtual void invoke() { mFunc(); }  
  8.     virtual bool compare(IDelegate *_delegate) const  
  9.     {  
  10.         if (0 == _delegate || !_delegate->isType(typeid(CStaticDelegate)) ) return false;  
  11.         CStaticDelegate * cast = static_cast<CStaticDelegate*>(_delegate);  
  12.         return cast->mFunc == mFunc;  
  13.     }  
  14. private:  
  15.     Func mFunc;  
  16. };  

 

可以看到,CStaticDelegate只是简单地封装了普通函数指针,代码也非常简单

(类的某些成员函数,如isType和compare使用了RTTI,

对C++的动态类型判断不熟的可以猛击这里http://blog.csdn.net/gouki04/article/details/6796173)

好了,注意了,下面开始封装类成员函数指针

 

  1. template<class T>  
  2. class CMethodDelegate : public IDelegate  
  3. {  
  4. public:  
  5.     typedef void (T::*Method)();  
  6.     CMethodDelegate(T * _object, Method _method) : mObject(_object), mMethod(_method) { }  
  7.     virtual bool isType( const std::type_info& _type) { return typeid(CMethodDelegate) == _type; }  
  8.     virtual void invoke()  
  9.     {  
  10.         (mObject->*mMethod)();  
  11.     }  
  12.     virtual bool compare(IDelegate *_delegate) const  
  13.     {  
  14.         if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate)) ) return false;  
  15.         CMethodDelegate* cast = static_cast<CMethodDelegate* >(_delegate);  
  16.         return cast->mObject == mObject && cast->mMethod == mMethod;  
  17.     }  
  18. private:  
  19.     T * mObject;  
  20.     Method mMethod;  
  21. };  

 

首先解释一下:因为类成员函数指针与类的类型有关,不同类的成员函数指针是不一样的。

要解决类型不同,很简单,使用模板就行。

代码跟CStaticDelegate基本一样,下面稍微解释一下:

CMethodDelegate类主要封装了一个类实例指针以及类成员函数的指针

这样在invoke时就不要额外的通过一个类实例了

要注意一点,compare函数的实现中,相等判定是类实例以及类函数指针都一样。

也就是说就算是指针同一个成员函数,但实例不同,委托就不同

为了方便使用,定义函数newDelegate来创建委托使用的函数

 

  1. inline IDelegate* newDelegate( void (*_func)() )  
  2. {  
  3.     return new CStaticDelegate(_func);  
  4. }  
  5. template<class T>  
  6. inline IDelegate* newDelegate( T * _object, void (T::*_method)() )  
  7. {  
  8.     return new CMethodDelegate<T>(_object, _method);  
  9. }  

 

至此,对C++函数指针的封装就完成了,不难吧。

下面就是委托的实现了

 

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

 

仔细理解下CMultiDelegate类的实现,代码都不深奥。

比较重要的是3个函数 :+=,-=,()运算符的重载函数

+= 用于添加一个委托函数

-= 用于去掉一个委托函数

() 用于触发委托函数

差不多就是普通的stl容器使用了。

这里要重点说明的一点是,大家仔细看 += 函数的实现中

 

  1. if ((*iter) && (*iter)->compare(_delegate))  
  2. {  
  3. delete _delegate; // 如果该委托函数已经被添加了,则delete掉外部的_delegate  
  4. return *this;  
  5. }  

 

为什么要delete掉外部的指针呢?

因为C++的内存泄露一直是个麻烦事,所以MyUGI的委托里,所有的委托函数统一由Delegate本身管理

外部不要自己new或delete委托函数,也不要保存一个委托函数,Delegate本身会管理好的。

建议像如下使用:

 

  1. CMultiDelegate myDelegate;  
  2. myDelegate += newDelegate(normalFunc);  
  3. myDelegate -= newDelegate(normalFunc);  

 

而不建议像如下使用:

 

  1. CMultiDelegate myDelegate;  
  2. IDelegate* delegateFunc = newDelegate(normalFunc);  
  3. myDelegate += delegateFunc;  
  4. myDelegate -= delegateFunc;  

 

上面2种方法都没错,都不会造成内存泄露

你可能会觉得第2种方法减少new的次数,比第一种方法更好。其实不然,因为第2种方法有个很大的隐患

 

  1. myDelegate -= delegateFunc; // 在这一步,delegateFunc所指向的空间已经被释放掉了(在-=函数里面)  

 

所以如果你后面又想将delegateFunc添加到myDelegate里面时,你就不能再这样用了

 

  1. myDelegate += delegateFunc; // 错误,因为delegateFunc的空间已经被释放了  

 

你得重新new一个

delegateFunc = newDelegate(normalFunc);

myDelegate += delegateFunc;

相信你不会愿意这样做的,因为这种方法很容易造成内存泄露或者崩溃

现在你应该可以明白 -= 函数是怎么释放委托函数内存了吧。

 

1.实现任意参数的函数委托

按上一篇文章的方法,你已经可以使用无参数的函数委托了。当然,这远远不够。要实现任意参数的函数委托,这里的任意参数包括任意个数和任意类型。任意类型这个容易解决,使用模板就行,但任意参数个数呢?

注:最终的实现代码可以在这里下载:http://download.csdn.net/detail/gouki04/3641328

只能不同个数各实现一个类,如

 

  1. // 单参函数委托  
  2. template<typename TP1>  
  3. class CMultiDelegate1{};  
  4. // 双参函数委托  
  5. template<typename TP1, typename TP2>  
  6. class CMultiDelegate2{};  

 

注意类名是不一样的,分别为CMultiDelegate1和CMultiDelegate2

C++里面,类名相同但模板参数个数不同是会当成一个类对待的,所以那样编译不过的

这样是不是很麻烦呢?

不是很麻烦,是相当麻烦。因为不单单是CMultiDelegate要实现多个参数的版本

连IDelegate、CStaticDelegate和CMethodDelegate都要实现对应的多个参数的版本!

其实所有版本的内部实现几乎一样,下面给出双参函数的版本

 

  1. template<typename TP1, typename TP2>  
  2. class IDelegate2  
  3. {  
  4. public:  
  5.     virtual ~IDelegate2() { }  
  6.     virtual bool isType( const std::type_info& _type) = 0;  
  7.     virtual void invoke( TP1 p1, TP2 p2 ) = 0;  
  8.     virtual bool compare( IDelegate2<typename TP1, typename TP2> *_delegate) const = 0;  
  9. };  
  10. template<typename TP1, typename TP2>  
  11. class CStaticDelegate2 : public  IDelegate2<typename TP1, typename TP2>  
  12. {  
  13. public:  
  14.     typedef void (*Func)( TP1 p1, TP2 p2 );  
  15.     CStaticDelegate2 (Func _func) : mFunc(_func) { }  
  16.     virtual bool isType( const std::type_info& _type) { return typeid( CStaticDelegate2<typename TP1, typename TP2> ) == _type; }  
  17.     virtual void invoke( TP1 p1, TP2 p2 )  
  18.     {  
  19.         mFunc( p1, p2 );  
  20.     }  
  21.     virtual bool compare( IDelegate2<typename TP1, typename TP2> *_delegate) const  
  22.     {  
  23.         if (0 == _delegate || !_delegate->isType(typeid(CStaticDelegate2 <typename TP1, typename TP2>)) ) return false;  
  24.         CStaticDelegate2 <typename TP1, typename TP2> * cast = static_cast<CStaticDelegate2 <typename TP1, typename TP2> *>(_delegate);  
  25.         return cast->mFunc == mFunc;  
  26.     }  
  27.     virtual bool compare(IDelegateUnlink * _unlink) const { return false; }  
  28. private:  
  29.     Func mFunc;  
  30. };  
  31. template <typename T, typename TP1, typename TP2>  
  32. class CMethodDelegate2 : public  IDelegate2 <typename TP1, typename TP2>  
  33. {  
  34. public:  
  35.     typedef void (T::*Method)( TP1 p1, TP2 p2 );  
  36.     CMethodDelegate2(T * _object, Method _method) : mObject(_object), mMethod(_method) { }  
  37.     virtual bool isType( const std::type_info& _type) { return typeid( CMethodDelegate2 <T, TP1, TP2> ) == _type; }  
  38.     virtual void invoke( TP1 p1, TP2 p2 )  
  39.     {  
  40.         (mObject->*mMethod)( p1, p2 );  
  41.     }  
  42.     virtual bool compare(  IDelegate2 <typename TP1, typename TP2>  * _delegate) const  
  43.     {  
  44.         if (0 == _delegate || !_delegate->isType(typeid(CMethodDelegate2 <T, TP1, TP2>)) ) return false;  
  45.         CMethodDelegate2 <T, TP1, TP2>  * cast = static_cast<  CMethodDelegate2 <T, TP1, TP2>  * >(_delegate);  
  46.         return cast->mObject == mObject && cast->mMethod == mMethod;  
  47.     }  
  48. private:  
  49.     T * mObject;  
  50.     Method mMethod;  
  51. };  
  52. template   <typename TP1, typename TP2>  
  53. inline  delegates::IDelegate2 <typename TP1, typename TP2>  * newDelegate( void (*_func)( TP1 p1, TP2 p2 ) )  
  54. {  
  55.     return new delegates::CStaticDelegate2 <typename TP1, typename TP2>  (_func);  
  56. }  
  57. template <typename T, typename TP1, typename TP2>  
  58. inline  delegates::IDelegate2 <typename TP1, typename TP2>  * newDelegate( T * _object, void (T::*_method)( TP1 p1, TP2 p2 ) )  
  59. {  
  60.     return new delegates::CMethodDelegate2  <T, TP1, TP2>  (_object, _method);  
  61. }  
  62. template   <typename TP1, typename TP2>  
  63. class CMultiDelegate2  
  64. {  
  65. public:  
  66.     typedef IDelegate2 <typename TP1, typename TP2>  IDelegate;  
  67.     typedef typename std::list<IDelegate*> ListDelegate;  
  68.     typedef typename ListDelegate::iterator ListDelegateIterator;  
  69.     typedef typename ListDelegate::const_iterator ConstListDelegateIterator;  
  70.     CMultiDelegate2 () { }  
  71.     ~CMultiDelegate2 () { clear(); }  
  72.     bool empty() const  
  73.     {  
  74.         for (ConstListDelegateIterator iter = mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)  
  75.         {  
  76.             if (*iter) return false;  
  77.         }  
  78.         return true;  
  79.     }  
  80.     void clear()  
  81.     {  
  82.         for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)  
  83.         {  
  84.             if (*iter)  
  85.             {  
  86.                 delete (*iter);  
  87.                 (*iter) = 0;  
  88.             }  
  89.         }  
  90.     }  
  91.     CMultiDelegate2  <typename TP1, typename TP2> & operator+=(IDelegate* _delegate)  
  92.     {  
  93.         for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)  
  94.         {  
  95.             if ((*iter) && (*iter)->compare(_delegate))  
  96.             {  
  97.                 delete _delegate;  
  98.                 return *this;  
  99.                 //MYGUI_ASSERT(false, "dublicate delegate");  
  100.             }  
  101.         }  
  102.         mListDelegates.push_back(_delegate);  
  103.         return *this;  
  104.     }  
  105.     CMultiDelegate2  <typename TP1, typename TP2> & operator-=(IDelegate* _delegate)  
  106.     {  
  107.         for (ListDelegateIterator iter=mListDelegates.begin(); iter!=mListDelegates.end(); ++iter)  
  108.         {  
  109.             if ((*iter) && (*iter)->compare(_delegate))  
  110.             {  
  111.                 if ((*iter) != _delegate) delete (*iter);  
  112.                 (*iter) = 0;  
  113.                 break;  
  114.             }  
  115.         }  
  116.         delete _delegate;  
  117.         return *this;  
  118.     }  
  119.     void operator()( TP1 p1, TP2 p2 )  
  120.     {  
  121.         ListDelegateIterator iter = mListDelegates.begin();  
  122.         while (iter != mListDelegates.end())  
  123.         {  
  124.             if (0 == (*iter))  
  125.             {  
  126.                 iter = mListDelegates.erase(iter);  
  127.             }  
  128.             else  
  129.             {  
  130.                 (*iter)->invoke( p1, p2 );  
  131.                 ++iter;  
  132.             }  
  133.         }  
  134.     }  
  135. private:  
  136.     CMultiDelegate2 (const CMultiDelegate2  <typename TP1, typename TP2> & _event);  
  137.     CMultiDelegate2<typename TP1, typename TP2> & operator=(const CMultiDelegate2<typename TP1, typename TP2> & _event);  
  138. private:  
  139.     ListDelegate mListDelegates;  
  140. };  

 

当然放心啦,不会让大家将不同参数的版本各写一遍的

下面要介绍的是MyGUI的解决方法,一个利用预编译和头文件重复编译的方法(很有意思的)

我们一般写头文件时,都会加上防止头文件重复编译的代码,如

 

  1. #ifndef __XXX_H__  
  2. #define __XXX_H__  
  3. // ..类声明等  
  4. #endif  

 

这里我们就要反其道而行,去掉防止重复编译的代码,然后重复包含这个头文件,但每次其编译的都是不同参数个数的版本

第一次编译的是无参的,第二次是单参的,第三次是双参.....一直到你想要支持的参数个数

那怎么让其每次编译的都不同呢?

答案就是使用强大的预编译:宏

下面给出单参的IDelegate的例子

首先定义以下宏:

 

  1. #define DELEGATE_TEMPLATE template  
  2. #define DELEGATE_TEMPLATE_PARAMS <typename TP1>  
  3. #define DELEGATE_TEMPLATE_ARGS TP1 p1  
  4. #define MYGUI_I_DELEGATE IDelegate1  

 

那么下面这段代码就会编译出单参的IDelegate版本

 

  1. DELEGATE_TEMPLATE   DELEGATE_TEMPLATE_PARAMS  
  2. class MYGUI_I_DELEGATE  
  3. {  
  4. public:  
  5.     virtual ~MYGUI_I_DELEGATE() { }  
  6.     virtual bool isType( const std::type_info& _type) = 0;  
  7.     virtual void invoke( DELEGATE_PARAMS ) = 0;  
  8.     virtual bool compare(  MYGUI_I_DELEGATE DELEGATE_TEMPLATE_ARGS  * _delegate) const = 0;  
  9. };  

 

神奇吧,这里使用的可以说是宏实现的多态。

在这段代码编译完了之后,将所有宏都undefine掉,如

 

  1. #undef DELEGATE_TEMPLATE  
  2. #undef DELEGATE_TEMPLATE_PARAMS  
  3. #undef DELEGATE_TEMPLATE_ARGS  
  4. #undef MYGUI_I_DELEGATE  

 

再重新定义双参版本的,如

 

  1. #define DELEGATE_TEMPLATE template  
  2. #define DELEGATE_TEMPLATE_PARAMS <typename TP1, typename TP2>  
  3. #define DELEGATE_TEMPLATE_ARGS TP1 p1, TP2 p2  
  4. #define MYGUI_I_DELEGATE IDelegate2  

 

那么编译出来的就是双参的版本了!

使用这种方法就可以将其他的如CStaticDelegate、CMethodDelegate和CMultiDelegate的各种版本都实现了,

而你要做的仅是重新define下那些宏就行了,够方便了吧。

下一篇文章将会介绍MyGUI实现的一些辅助类,如单委托和DelegateUnlink。并给出一个测试例子,测试该委托机制对C++各种函数的支持。

 

 

1.引言

按上一篇文章的方法,你已经可以使用任意参数的函数委托了。这里介绍下MyGUI实现的两个辅助类,CDelegate类和IDelegateUnlink。如果你不为了深入了解MyGUI的委托实现,可以跳过此处。CDelegate即为单委托,实际效果跟函数指针差不多,于CMultiDelegate的区别在于其不支持多播。而IDelegateUnlink类主要是在CMultiDelegate中使用,在多播下一次性去掉自身的所有委托。


2.单委托

  1. // 无参的单委托实现  
  2. class CDelegate  
  3. {  
  4. public:  
  5.     typedef CDelegate IDelegate;  
  6.   
  7.   
  8.     CDelegate () : mDelegate(0) { }  
  9.     CDelegate (const CDelegate& _event)  
  10.     {  
  11.         // 在拷贝构造时,将被拷贝的委托去掉,即委托只存在一份  
  12.         mDelegate = _event.mDelegate;  
  13.         const_cast<CDelegate&>(_event).mDelegate = 0;  
  14.     }  
  15.     ~CDelegate () { clear(); }  
  16.   
  17.   
  18.     bool empty() const { return mDelegate == 0; }  
  19.   
  20.   
  21.     void clear()  
  22.     {  
  23.         if (mDelegate)  
  24.         {  
  25.             delete mDelegate;  
  26.             mDelegate = 0;  
  27.         }  
  28.     }  
  29.   
  30.   
  31.     CDelegate & operator=(IDelegate* _delegate)  
  32.     {  
  33.         delete mDelegate;  
  34.         mDelegate = _delegate;  
  35.         return *this;  
  36.     }  
  37.   
  38.   
  39.     CDelegate & operator=(const CDelegate& _event)  
  40.     {  
  41.         // 在赋值时,将右值的委托去掉,即委托只存在一份  
  42.         delete mDelegate;  
  43.         mDelegate = _event.mDelegate;  
  44.         const_cast<CDelegate&>(_event).mDelegate = 0;  
  45.   
  46.   
  47.         return *this;  
  48.     }  
  49.   
  50.   
  51.     void operator()( )  
  52.     {  
  53.         if (mDelegate == 0) return;  
  54.         mDelegate->invoke( );  
  55.     }  
  56.   
  57.   
  58. private:  
  59.     IDelegate * mDelegate;  
  60. };  

可以看到,单委托只实现了 = 运算符,没有实现 += 运算符。
而且在赋值时会将原委托去掉,确保只有一份委托。
其实单委托跟普通函数指针差不多,在使用单委托的地方可以换成使用普通函数指针。


3.断开委托

  1. // 断开委托的基类  
  2. class IDelegateUnlink  
  3. {  
  4. public:  
  5.     virtual ~IDelegateUnlink() { }  
  6.   
  7.   
  8.     IDelegateUnlink() { m_baseDelegateUnlink = this; }  
  9.     bool compare(IDelegateUnlink * _unlink) const { return m_baseDelegateUnlink == _unlink->m_baseDelegateUnlink; }  
  10.   
  11.   
  12. private:  
  13.     IDelegateUnlink * m_baseDelegateUnlink;  
  14. };  

所谓断开委托,只能用在多重委托,即CMultiDelegate中,可以断开自身与其相连的所有委托。
使用方法就在将自身的类从IDelegateUnlink派生,然后使用CMultiDelegate中的clear函数即可断开委托。
在下面会有例子说明。


4.测试

    1. /* 测试Delegate对不同函数的支持 
    2.  * 可以参考下不同函数的使用方式 
    3.  */  
    4. #include "delegate.h"  
    5. #include <iostream>  
    6.   
    7.   
    8. using namespace std;  
    9.   
    10.   
    11. // 普通函数1  
    12. void func(int a, int b)  
    13. {  
    14.     cout << "func(" << a << ", " << b << ")" << endl;  
    15. }  
    16.   
    17.   
    18. // 普通函数2  
    19. void func2(int a, int b)  
    20. {  
    21.     cout << "func2(" << a << ", " << b << ")" << endl;  
    22. }  
    23.   
    24.   
    25. // 普通类  
    26. class NormalClass  
    27. {  
    28. public:  
    29.     // 类的普通成员函数  
    30.     void normalFunc(int a, int b)  
    31.     {  
    32.         cout << "NormalClass::normalFunc(" << a << ", " << b << ")" << endl;  
    33.     }  
    34. };  
    35.   
    36.   
    37. // 实现了IDelegateUnlink的类  
    38. class BaseUnlinkClass : public delegates::IDelegateUnlink  
    39. {  
    40. public:  
    41.     // 类的虚函数  
    42.     virtual void virFunc(int a, int b)  
    43.     {  
    44.         cout << "BaseUnlinkClass::virFunc(" << a << ", " << b << ")" << endl;  
    45.     }  
    46.   
    47.   
    48.     // 类的普通成员函数  
    49.     void normalFunc(int a, int b)  
    50.     {  
    51.         cout << "BaseUnlinkClass::normalFunc(" << a << ", " << b << ")" << endl;  
    52.     }  
    53. };  
    54.   
    55.   
    56. class DerivedClass : public BaseUnlinkClass  
    57. {  
    58. public:  
    59.     // 类的虚函数  
    60.     virtual void virFunc(int a, int b)  
    61.     {  
    62.         cout << "DerivedClass::virFunc(" << a << ", " << b << ")" << endl;  
    63.     }  
    64.   
    65.   
    66.     // 类的静态成员函数  
    67.     static void staticFunc(int a, int b)  
    68.     {  
    69.         cout << "DerivedClass::staticFunc(" << a << ", " << b << ")" << endl;  
    70.     }  
    71. };  
    72.   
    73.   
    74. // 模板函数  
    75. template<class T>  
    76. void TFunc(T a, T b)  
    77. {  
    78.     cout << "TFunc(" << a << ", " << b << ")" << endl;  
    79. }  
    80.   
    81.   
    82. int main()  
    83. {  
    84.     BaseUnlinkClass *baseUnlinkClass = new BaseUnlinkClass;  
    85.     DerivedClass *derivedClass = new DerivedClass;  
    86.     NormalClass *normalClass = new NormalClass;  
    87.       
    88.     // 定义委托  
    89.     typedef delegates::CMultiDelegate2<int, int> EvenetHandler;  
    90.     EvenetHandler event;  
    91.   
    92.   
    93.     // 添加普通函数  
    94.     event += newDelegate(func);  
    95.     event += newDelegate(func2);  
    96.   
    97.   
    98.     // 添加类的普通成员函数  
    99.     event += newDelegate(normalClass, &NormalClass::normalFunc);  
    100.     event += newDelegate(baseUnlinkClass, &BaseUnlinkClass::normalFunc);  
    101.   
    102.   
    103.     // 添加类的虚函数  
    104.     event += newDelegate(baseUnlinkClass, &BaseUnlinkClass::virFunc);  
    105.     event += newDelegate(derivedClass, &DerivedClass::virFunc);  
    106.     // 注意在多态下,使用基类指针时,函数指针要用基类的函数指针,不能用派生类的  
    107.     // 但是在调用时会响应多态,也就是会调用派生类的虚函数  
    108.     event += newDelegate((BaseUnlinkClass*)derivedClass, &BaseUnlinkClass::virFunc);  
    109.   
    110.   
    111.     // 添加类的静态成员函数  
    112.     event += newDelegate(&DerivedClass::staticFunc);  
    113.   
    114.   
    115.     // 添加模板函数  
    116.     event += newDelegate(TFunc<int>);  
    117.       
    118.     // 触发事件  
    119.     event(1, 2);  
    120.     cout << endl;  
    121.   
    122.   
    123.     // 去掉函数  
    124.     event -= newDelegate(func);  
    125.   
    126.   
    127.     // 去掉baseUnlinkClass所有的函数  
    128.     event.clear(baseUnlinkClass);  
    129.   
    130.   
    131.     // 去掉derivedClass所有的函数  
    132.     // 注意静态成员函数staticFunc不会去掉  
    133.     event.clear(derivedClass);  
    134.   
    135.   
    136.     //event.clear(normalClass);  
    137.     // 错误调用,normalClass不是IDelegateUnlink的派生类  
    138.     // 不能使用clear去掉自身的函数  
    139.     // 应该使用如下方法  
    140.     event -= newDelegate(normalClass, &NormalClass::normalFunc);  
    141.       
    142.     // 触发事件  
    143.     event(2, 3);  
    144.     cout << endl;  
    145.   
    146.   
    147.     return 0;  
    148. }  

转载于:https://www.cnblogs.com/zhoug2020/p/6592089.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/355973.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

jmeter负载测试测试_Apache JMeter:随心所欲进行负载测试

jmeter负载测试测试这是有关使用Apache JMeter进行负载测试的第二篇文章&#xff0c;请在此处阅读第一篇文章&#xff1a; 有关对关系数据库进行负载测试的分步教程。 JMeter有很多采样器 。 如果您需要JMeter不提供的采样器&#xff0c;则可以编写您的自定义采样器。 &#xf…

linux中文件属性mtime,linux stat (三个时间属性命令可用来列出文件的 atime、ctime 和 mtime。)...

[[email protected] ~]# stat test/test2File: ‘test/test2‘Size: 0 Blocks: 0 IO Block: 4096 普通空文件Device: 803h/2051d Inode: 261657 Links: 1Access: (0744/-rwxr--r--) Uid: ( 500/ user1) Gid: ( 500/testgroup)Access:…

教程:测试期间的日志记录

日志记录是一种流行的解决方案&#xff0c;用于显示软件在运行时的运行状况。 但是&#xff0c;当我们使用jUnit / TestNG对应用程序进行单元测试时&#xff0c;日志记录会怎样&#xff1f; 在自动化测试执行期间&#xff0c;我们通常不希望看到日志记录消息&#xff0c;因为…

VM虚拟机ping不通局域网其他主机的解决办法

1 我的笔记本的无线网卡是自动获取IP&#xff0c;并且是通过无线网卡上网。 2 我的有线网卡是通过自己设定IP跟局域网的其他机器连通。当前设定的IP为172.16.17.2 3我需要连接的局域网另一个主机为172.16.17.8&#xff0c;现在测试主机跟这个局域网的另一台主机是可以ping通的。…

moxy json介绍_MOXy作为您的JAX-RS JSON提供程序–客户端

moxy json介绍最近&#xff0c;我发布了如何利用EclipseLink JAXB&#xff08;MOXy&#xff09;的JSON绑定来创建RESTful服务。 在本文中&#xff0c;我将演示在客户端利用MOXy的JSON绑定有多么容易。 MOXy作为您的JAX-RS JSON提供程序–服务器端 MOXy作为您的JAX-RS JSON提供…

linux命令画圣诞树图片,以 Linux 的方式庆祝圣诞节

原标题&#xff1a;以 Linux 的方式庆祝圣诞节当前正是假日季&#xff0c;很多人可能已经在庆祝圣诞节了。祝你圣诞快乐&#xff0c;新年快乐。为了延续节日氛围&#xff0c;我将向你展示一些非常棒的圣诞主题的 Linux 壁纸。在呈现这些壁纸之前&#xff0c;先来看一棵 Linux 终…

Mockito教程:使用Mockito进行测试和模拟

课程大纲 Mockito是根据MIT许可证发布的Java开源测试框架&#xff0c;该框架允许在自动化单元测试中创建测试双重对象&#xff08;模拟对象&#xff09;&#xff0c;以实现测试驱动开发&#xff08;TDD&#xff09;或行为驱动开发&#xff08;BDD&#xff09;的目的。 如官方文…

LINQ 学习路程 -- 查询语法 LINQ Query Syntax

1.查询语法 Query Syntax: from <range variable> in <IEnumerable<T> or IQueryable<T> Collection><Standard Query Operators> <lambda expression><select or groupBy operator> <result formation> // string collectio…

linux 权限提示信息,命令行快速提示:权限进阶 | Linux 中国

原标题&#xff1a;命令行快速提示&#xff1a;权限进阶 | Linux 中国本部分介绍使用权限管理文件访问和共享的其他方法。-- Paul W. Frields前一篇文章。本部分介绍使用权限管理文件访问和共享的其他方法。它建立在前一篇文章中的知识和示例的基础上&#xff0c;所以如果你还没…

nginx正确服务react-router应用

如今React应用普遍使用react-router作为路由管理&#xff0c;在开发端webpack自带的express服务器下运行和测试表现均正常&#xff0c;部署到线上的nginx服务器后&#xff0c;还需要对该应用在nginx的配置里作相应调整&#xff0c;否则浏览器将不能正常使用该应用&#xff0c;表…

linux多进程 段错误,关于段错误

一个月的时间&#xff0c;就为了解决一个问题&#xff0c;段错误运行环境&#xff1a;arm-linux模块&#xff1a;XML&#xff0c;为多线程&#xff0c;多socket的网络通信协议程序现象&#xff1a;XML在运行一段时间以后&#xff0c;出现段错误&#xff0c;运行的时间和出现问题…

解决checkbox与对应文字不对齐的问题

最近公司比较忙&#xff0c;所以一直在赶项目&#xff0c;很久没有更新博客了。 刚才在工作中又遇到了一个问题&#xff0c;下面我来分享一下吧(&#xff61;&#xff65;∀&#xff65;)&#xff89;&#xff9e; 问题所在我写了一个input&#xff0c;他的类型是checkbox&…

scala akka_使用Scala,Play和Akka连接到RabbitMQ(AMQP)

scala akka在本文中&#xff0c;我们将研究如何从Scala连接到RabbitMQ&#xff0c;以便可以从应用程序中支持AMQP协议。 在此示例中&#xff0c;我将使用Play Framework 2.0作为容器&#xff08;有关更多信息&#xff0c;请参阅我在该主题上的其他文章 &#xff09;在其中运行应…

linux中服务器之间的跳转,linux之***服务器间ip隧道跳转多ip路由走向分流(系真实案例)...

本文系统Centos6.0&#xff1b;这里的***服务以pptpd为例&#xff1b;其中底层涉及到pptpdfreeradiusmysql认证&#xff1b;本文系真实案例&#xff1b;leader需求大多是这样的&#xff0c;节约成本还要达到所需要的效果&#xff1b;没办法&#xff0c;总的做个效果出来&#x…

POJ2503 Babelfish map或者hash_map

POJ2503 这是一道水题&#xff0c;用Map轻松AC。 不过&#xff0c;可以拿来测一下字符串散列&#xff0c; 毕竟&#xff0c;很多情况下map无法解决的映射问题需要用到字符串散列。 自己生成一个质数&#xff0c; 随便搞一下。 #include<iostream> #include<cstdio>…

使用JBoss EAP 7的HTTP / 2

就在几天前&#xff0c;新的JBoss EAP 7 ALPHA版本已经发布。 而且我已经写过关于如何开始使用它的博客。 一个非常有趣的部分是HTTP / 2支持&#xff0c;它已作为技术预览添加。 它由新的Web服务器Untertow提供。 HTTP / 2通过压缩头并在同一TCP连接上多路复用多个流来减少延迟…

linux树莓派 ssh密码,树莓派之SSH连接经验

打开SSH服务执行raspi-configsudo raspi-config选择InterfacingOptions选项&#xff0c;回车选择SSH&#xff0c;回车Windows下客户端推荐使用putty这个免费开源的SSH客户端。下载地址在红框处填入树莓派的IP地址&#xff0c;点击右下角的Open即可。不过&#xff0c;putty的默认…

linux嵌入式面试题合集,嵌入式linux面试题解析(一)——ARM部分二

嵌入式linux面试题解析(一)——ARM部分二1、描述一下嵌入式基于ROM的运行方式基于RAM的运行方式有什么区别。基于RAM的运行方式&#xff1a;需要把硬盘和其他介质的代码先加载到ram中&#xff0c;加载过程中一般有重定位的操作&#xff1b;基于ROM&#xff1a;没有上面的操作。…

Unity应用架构设计(1)—— MVVM 模式的设计和实施(Part 2)

MVVM回顾 经过上一篇文章的介绍&#xff0c;相信你对MVVM的设计思想有所了解。MVVM的核心思想就是解耦&#xff0c;View与ViewModel应该感受不到彼此的存在。 View只关心怎样渲染&#xff0c;而ViewModel只关心怎么处理逻辑&#xff0c;整个架构由数据进行驱动。不仅View与View…

apache camel_REST端点,可使用Apache Camel进行集成

apache camelREST是一种用于组织资源的体系结构样式&#xff0c;当应用于基于HTTP的服务时&#xff0c;REST可以构建无状态&#xff0c;分离的可伸缩服务。 HTTP方法&#xff0c;HTTP标头和mime类型都允许开发人员实现REST样式。 诸如Jersey和Fuse Services Framework&#xff…