C++中关于委派(Delegates)的实现示例

2020-01-06 13:19:38于丽
  • sqr(2.1): 4.41 

    关键点

    对于一个不是 volatile 和 const 的简单函数而言,实现是非常简单的,我们只需要创建一个类保存两个指针,一个是对象,另外一个是成员函数:

     

     
    1. template <class T, class R, class ... P>  struct _mem_delegate 
    2. {  T* m_t; 
    3. R (T::*m_f)(P ...);  _mem_delegate(T* t, R (T::*f)(P ...) ):m_t(t),m_f(f) {} 
    4. R operator()(P ... p)  { 
    5. return (m_t->*m_f)(p ...);  } 
    6. }; 

    可变模板 variadic template 允许定义任意个数和类型参数的operator()函数,而create_function 实现只需简单返回该类的对象:

     

     
    1. template <class T, class R, class ... P>  _mem_delegate<T,R,P ...> create_delegate(T* t, R (T::*f)(P ...))