Template Template Parameters

クラス内で使用するコンテナをテンプレート引数で指定したい

そういうときに、以下のようなクラステンプレートを書くと

template <class Container>
class hoge;

hoge > h;
はできても
hoge h;
はできない



hogeクラスの中では以下のようにして使いたい

template <?? Container>
class hoge {
    Container<int> c;
};

そこでTemplate Template Parametersを使う

テンプレートパラメータには、テンプレートを指定することができる

template <class T>
class vector;

template <template<class> class Container>
class hoge {
    Container<int> c;
};

hoge<vector> h; // OK

だが、残念だがこれだけではstd::vectorには適用できない

hoge<std::vector> h; // エラー!引数の数が一致しません

std::vectorの定義が以下のようになっているからだ

namespace std {
    template <class T, class Allocator=allocator<T> >
    class vector;
}


そこで、以下のように直す必要がある

template <template<class T, class Allocator=std::allocator<T> > class Container>
class hoge {
    Container<int> c;
};

hoge<std::vector> h; // OK


Template Template Parametersを使えば、テンプレート引数を省略して指定することができる




参考書籍

Modern C++ Design―ジェネリック・プログラミングおよびデザイン・パターンを利用するための究極のテンプレート活用術

C++ Templates: The Complete Guide