奇特重现模板模式
出自cppreference.com
奇特重現模板模式(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)
| |
(C++11) |
允許對象創建指代自身的 shared_ptr (類模板) |
(C++20) |
用於定義 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 |