タグ・ディスパッチ

C++テンプレートテクニック 3-5


簡単に言えばオーバーロードを利用した関数の呼び分け処理といった感じでしょうか。

シンプルな例を考えてみました。

#include <iostream>
using std::cout; using std::endl;

// ディスパッチ用のタグ名
struct tag_a {};
struct tag_b {};

// ディスパッチ関数
void foo (tag_a) {
    cout << "foo tag_a" << endl;
}
void foo (tag_b) {
    cout << "foo tag_b" << endl;
}

class CClassA {
public:
    typedef tag_a tag_name;
};
class CClassB {
public:
    typedef tag_b tag_name;
};

template<class T>
void dispatch (T) {
    foo(T::tag_name());
}

int main () {
    dispatch(CClassA());
    dispatch(CClassB());
    
    return 0;
}
$ main
foo tag_a
foo tag_b

CClassAとCClassBはtypedefにより、tag_nameという一つの名前を定義する。

あとはそれをディスパッチ対象となる関数に渡すだけでオーバーロードによりうまく振り分けられるといった感じ。