CRTP to avoid dynamic polymorphismでは、仮想メンバー関数のオーバーヘッドを回避し、特定のインターフェイスを課すために、次の解決策が提案されています。
template <class Derived>
struct base {
void foo() {
static_cast<Derived *>(this)->foo();
};
};
struct my_type : base<my_type> {
void foo() {}; // required to compile. < Don't see why
};
struct your_type : base<your_type> {
void foo() {}; // required to compile. < Don't see why
};
ただし、派生クラスは定義を継承するため、コンパイルするための定義は必要ないようです (コードは、my_type::foo を定義しなくても正常にコンパイルされます)。実際、関数が提供されている場合、派生クラスを使用するときに基本関数は呼び出されません。
問題は、次のコード置換が受け入れられるかどうか (そして標準かどうか) です。
template <class Derived>
struct base {
void foo() {
// Generate a meaningful error if called
(void)sizeof( Derived::foo_IS_MISSING );
};
};
struct my_type : base<my_type> {
void foo() {}; // required to compile.
};
struct your_type : base<your_type> {
void foo() {}; // required to compile.
};
int main() {
my_type my_obj;
my_obj.foo(); // will fail if foo missing in derived class
}