奇異遞迴模板模式
來自 cppreference.com
奇異遞迴模板模式是一種慣用法,其中類 X
繼承自類模板 Y
,並以模板引數 Z
例項化 Y
,其中 Z = X。例如:
template<class Z> class Y {}; class X : public Y<X> {};
[編輯] 示例
CRTP 可用於實現“編譯時多型”,即基類公開一個介面,而派生類實現該介面。
執行此程式碼
#include <cstdio> #ifndef __cpp_explicit_this_parameter // Traditional syntax template <class Derived> struct Base { void name() { static_cast<Derived*>(this)->impl(); } protected: Base() = default; // prohibits the creation of Base objects, which is 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 deducing-this syntax 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. | 用概念替換 CRTP? — Sandor Drago 的部落格 |
2. | 奇異遞迴模板模式 (CRTP) — Sandor Drago 的部落格 |
3. | 奇異遞迴模板模式 (CRTP) - 1 — Fluent{C++} |
4. | CRTP 能為你的程式碼帶來什麼 - 2 — Fluent{C++} |
5. | CRTP 的實現助手 - 3 — Fluent{C++} |
6. | 什麼是奇異遞迴模板模式 (CRTP) — SO |