奇特重现模板模式

来自cppreference.com
< cpp‎ | language
 
 
C++ 语言
 

奇特重现模板模式(CRTP)是一种习语。其中某个类 X 从一个模板形参为 Z 的类模板 Y 派生,并且 Y 以 Z=X 实例化。例如:

template<class Z>
class Y {};
 
class X : public Y<X> {};

CRTP 可以用来在基类暴露接口且派生类实现对应接口时实现“编译期多态”。

#include <iostream>
 
template <class Derived>
struct Base { void name() { (static_cast<Derived*>(this))->impl(); } };
 
struct D1 : public Base<D1> { void impl() { std::cout << "D1::impl()\n"; } };
struct D2 : public Base<D2> { void impl() { std::cout << "D2::impl()\n"; } };
 
int main()
{
    Base<D1> b1; b1.name();
    Base<D2> b2; b2.name();
 
    D1 d1; d1.name();
    D2 d2; d2.name();
}

输出:

D1::impl()
D2::impl()
D1::impl()
D2::impl()

See also

允许对象创建指代自身的 shared_ptr
(类模板)
用于定义 view 的辅助类模板,使用奇异递归模板模式
(类模板)