Curiously Recurring Template Pattern 奇异递归模板模式
通过CRTP可以使得类具有类似于虚函数的效果,同时又没有虚函数调用时的开销(虚函数调用需要通过虚函数指针查找虚函数表进行调用),同时类的对象的体积相比使用虚函数也会减少(不需要存储虚函数指针),但是缺点是无法动态绑定。
其本形式
template <typename type>
class base
{
void interface() {static_cast<type*>(this)->implementation();}
}
class derive: public base<derive>
{
void implememtation(){};
}代码示例 ```c++ #include
template
struct Derived : Base
int main() { Derived d; d.interface(); // Prints “Derived implementation”
return 0;
} ```
下面的代码示例主要是为了演示派生类中,通过调用其类中的方法,可以最终调用到基类或者派生类中的方法。
[!info] Compiler Explorer - C++
template <typename Derive> class Base{ public: void baseInterface(){static_cast<Derive*>(this)->implementation();} }; class Derive: public Base<Derive> { public: void implementation(){std::cout<<“inside Derive”<<std::endl;} }; int main() { Derive d; d.
https://godbolt.org/z/4MPsGzxde
[!info] 奇异递归模板模式(Curiously Recurring Template Pattern)
本篇短文将简短的介绍奇异递归模板模式(Curiously Recurring Template Pattern, CRTP),CRTP是C++模板编程时的一种惯用法(idiom):把派生类作为基类的模板参数。更一般地被称作F-bound polymorphism。1980年代…
https://zhuanlan.zhihu.com/p/54945314
CRTP这种设计模式,使得实例可以通过基类的接口调用派生类的实现。这样有几个好处:
1,实现类似虚函数的调用,但运行比虚函数的效率更好。
2,可以将一些高层的抽象、流程放在基类,而把具体的实现放在派生类中 (L2-PS中的应用)