CRTP(Curiously recurring template pattern)を使って静的に多態性を実現する

templateを使って静的に(コンパイル時に)仮想関数の仕組みを提供させようというもの。これを使うと仮想関数を呼びだすオーバーヘッドがなくなるので良いらしい。基本クラス(Base)をTemplateクラスとして宣言しておいて、派生クラスで自身を指定するのがミソ。要するにテンプレードパターンの静的な実装。

#include<iostream>
using namespace std;
//ベースクラス
template <class T>
struct Base
{
    void Interface(){
        static_cast<T *>(this)->Implementation();
    }
};
//派生クラス。ただしtemplate引数には自身を指定
struct Derived1 : Base<Derived1>
{
    void Implementation(){
        cout << "Derived1 " << endl;
    }
};
struct Derived2 : Base<Derived2>
{
    void Implementation(){
        cout << "Derived2 " << endl;
    }
};
//メイン関数
int main()
{
    Derived1 x;
    x.Interface();

    Derived2 y;
    y.Interface();

    return 0;
}

実行結果

Derived1
Derived2

参考
Curiously recurring template pattern - Wikipedia