名前空間
変種
操作

Curiously Recurring Template Pattern

From cppreference.com
< cpp‎ | language
 
 
C++言語
全般
フロー制御
条件実行文
if
繰り返し文 (ループ)
for
範囲for (C++11)
ジャンプ文
関数
関数宣言
ラムダ式
inline指定子
動的例外仕様 (C++17まで*)
noexcept指定子 (C++11)
例外
名前空間
指定子
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
記憶域期間指定子
初期化
代替表現
リテラル
ブーリアン - 整数 - 浮動小数点数
文字 - 文字列 - nullptr (C++11)
ユーザー定義 (C++11)
ユーティリティ
属性 (C++11)
typedef宣言
型エイリアス宣言 (C++11)
キャスト
メモリ確保
クラス
クラス固有の関数プロパティ
explicit (C++11)
static

特殊メンバ関数
テンプレート
その他
 

Curiously Recurring Template Patternとは、クラスXがクラステンプレートYから派生し、テンプレートパラメータZを取り、YZ = 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)
オブジェクトが自身を参照する shared_ptr を作成できるようにします
(クラステンプレート) [編集]
Curiously Recurring Template Pattern を使用してviewを定義するためのヘルパークラステンプレート
(クラステンプレート) [編集]

[編集] 外部リンク

1.  CRTPをコンセプトで置き換える? — Sandor Dragoのブログ
2.  The Curiously Recurring Template Pattern (CRTP) — Sandor Dragoのブログ
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
English 日本語 中文(简体) 中文(繁體)