cpp-template

奇异递归模板模式 CRTP 静态多态

(curiously recurring template pattern,CRTP)
静态多态(static polymorphism)
还是 静态多态这个名字比较好理解,在编译期决定调用函数

优点:
由于静多态是在编译期完成的,因此效率较高,编译器也可以进行优化;
有很强的适配性和松耦合性,比如可以通过偏特化、全特化来处理特殊类型;
最重要一点是静态多态通过模板编程为C++带来了泛型设计的概念,比如强大的STL库。

缺点:
由于是模板来实现静态多态,因此模板的不足也就是静多态的劣势,比如调试困难、编译耗时、代码膨胀、编译器支持的兼容性,不能够处理异质对象集合。

// The Curiously Recurring Template Pattern (CRTP)
template<class T>
class Base
{
// methods within Base can use template to access members of Derived
};
class Derived : public Base<Derived>
{
// ...
};
template <class T>
struct Base
{
void interface()
{
// ...
static_cast<T*>(this)->implementation();
// ...
}

static void static_func()
{
// ...
T::static_sub_func();
// ...
}
};

struct Derived : Base<Derived>
{
void implementation();
static void static_sub_func();
};

在上例中,Base::interface(),虽然是在struct Derived之前就被声明了,但未被编译器实例化直至它被实际调用,这发生于Derived声明之后,此时Derived::implementation()的声明是已知的。
这种技术获得了类似于虚函数的效果,并避免了动态多态的代价