C++惯用法:奇特的递归模板模式(Curiously Recurring Template Pattern,CRTP,Mixin-from-above)

来源:互联网 发布:c语言 gbk转unicode 编辑:程序博客网 时间:2024/04/30 18:08

http://blog.csdn.net/lifesider/article/details/6527653

意图:

使用派生类作为模板参数特化基类。

 

与多态的区别:

多态是动态绑定(运行时绑定),CRTP是静态绑定(编译时绑定)

 

在实现多态时,需要重写虚函数,因而这是运行时绑定的操作。

然而如果想在编译期确定通过基类来得到派生类的行为,CRTP便是一种独佳选择,它是通过派生类覆盖基类成员函数来实现静态绑定的。

 

范式:

[cpp] view plain copy
  1. class derived : public base<derived>  
  2. {  
  3.     // attributes and behaviors  
  4. }  

 

示例代码:

[c-sharp] view plain copy
  1. template <class Derived>  
  2.   struct base  
  3.   {  
  4.       void interface()  
  5.       {  
  6.           // 转换为子类指针,编译期将绑定至子类方法  
  7.           static_cast<Derived*>(this)->implementation();  
  8.       }  
  9.    
  10.       static void static_interface()  
  11.       {  
  12.           // 编译期将绑定至子类方法  
  13.           Derived::static_implementation();  
  14.       }  
  15.    
  16.       // 下面两个方法,默认实现可以存在,或者应该被继承子类的相同方法覆盖  
  17.       void implementation();  
  18.       static void static_implementation();  
  19.   };  
  20.    
  21.   // The Curiously Recurring Template Pattern (CRTP)  
  22.   struct derived_1 : base<derived_1>  
  23.   {  
  24.       // 这里子类不实现,将使用父类的默认实现  
  25.       //void implementation();  
  26.    
  27.       // 此方法将覆盖父类的方法  
  28.       static void static_implementation();  
  29.   };  
  30.    
  31.   struct derived_2 : base<derived_2>  
  32.   {  
  33.       // 此方法将覆盖父类的方法  
  34.       void implementation();  
  35.    
  36.       // 这里子类不实现,将使用父类的默认实现  
  37.       //static void static_implementation();  
  38.   };  

 

缺点:

CRTP由于基类使用了模板,目前的编译器不支持模板类的导出,因而不能使用导出接口。

 

其它使用领域:

在数值计算中,往往要对不同的模型使用不同的计算方法(如矩阵),一般使用继承提供统一接口(如operator运算符),但又希望不损失效率。这时便又可取CRTP惯用法,子类的operator实现将覆盖基类的operator实现,并可以编译期静态绑定至子类的方法。

 

英文链接:http://en.wikibooks.org/wiki/More_C++_Idioms/Curiously_Recurring_Template_Pattern

0 0
原创粉丝点击