The Curiously Recurring Template Pattern

  • 略して「CRTP」
  • 訳すと「(派生クラスを)詮索する再帰テンプレートパターン」
  • C++プログラミングの筋と定石のJames O. Coplienが紹介した
  • ダウンキャストに名前までついており、「Barton and Nackman trick」と言う
  • WTLでよく使われる


template <typename T_child>
struct parent {
void play_doh() {
// Barton and Nackman trick
T_child& child = static_cast<T_child&>(*this);
// curious about children
child.play();
}
};

struct child : parent<child> {
void play() { }
};

void test_crtp() {
child Bart, Lisa;
Lisa.play();
Bart.play_doh();
}

C++ Template Metaprogramming Section 9.8