奇特重现模板模式

来自cppreference.com
< cpp‎ | language


 
 
 

奇特重现模板模式(Curiously Recurring Template Pattern, CRTP)是一种惯用手法。其中类 X 从接收模板形参 Z 的类模板 Y 派生,并且以 Z = X 实例化 Y。例如:

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

[编辑]示例

CRTP 可用于在基类暴露接口而派生类实现该接口时实现“编译期多态”。

#include <cstdio>   #ifndef __cpp_explicit_this_parameter // 传统语法   template<class Derived>struct Base {void name(){(static_cast<Derived*>(this))->impl();}protected: Base()=default;// 禁止创建 Base 对象,这是 UB};struct D1 :public Base<D1>{void impl(){std::puts("D1::impl()");}};struct D2 :public Base<D2>{void impl(){std::puts("D2::impl()");}};   #else // C++23 的推导 this 语法   struct Base {void name(this auto&& self){ self.impl();}};struct D1 :public Base {void impl(){std::puts("D1::impl()");}};struct D2 :public Base {void impl(){std::puts("D2::impl()");}};   #endif   int main(){ D1 d1; d1.name(); D2 d2; d2.name();}

输出:

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

[编辑]参阅

显式对象成员函数(推导 this(C++23)
允许对象创建指代自身的 shared_ptr
(类模板)[编辑]
用于定义 view 的辅助类模板,使用奇特重现模板模式
(类模板)[编辑]

[编辑]外部链接

1. Replace CRTP with concepts? — Sandor Drago's blog
2. The Curiously Recurring Template Pattern (CRTP) — Sandor Drago's blog
3. The Curiously Recurring Template Pattern (CRTP) - 1 — Fluent{C++}
4. What the CRTP can bring to your code - 2 — Fluent{C++}
5. An implementation helper for the CRTP - 3 — Fluent{C++}
6. What is the Curiously Recurring Template Pattern (CRTP) — SO
close