LoginSignup
32
21

More than 5 years have passed since last update.

テンプレートテンプレートパラメータ

Last updated at Posted at 2014-12-01

テンプレートテンプレートという言葉に馴染みがない方もいらっしゃるかと思います。
テンプレートとは、よくご存知のように

template< class Type >
struct something;

こういうもので、Typeには基本的にどんな型でも入れることができます。
しかしTypeに入れることができない型があります。
それが、テンプレート引数が埋まっていない不完全な型です。
例えば、上記の構造体のテンプレートパラメータに、
something< std::vector< int > > と入れることはできても、
something< std::vector > と入れることはできません。
そうなると、somethingがこういう定義を持ちたい場合はどうでしょうか。

template< class Type >
struct something
{
  Type< int > container;
}:

このsomethingはコンテナを包含するもので、このコンテナがlistだったりvectorだったりをテンプレートパラメータで指定したい・・・となると大変困る事がわかります。
そこで使われるのが、テンプレートテンプレートで、何も難しいことはありません。

template<
  template< class, class > class Type >
struct something
{
  Type< int, std::allocator < int > > container;
};

Typeは、テンプレート引数を2つ取る何らかの型、という意味です。
std::vectorやstd::listは実はアロケータを引数に取るので、テンプレート引数は2つです。
基本形はこの通りです。

template<
  template< class > class Type >
struct somthing;

Typeの直前のclassキーワードを忘れがちですので注意しましょう。

蛇足ですが、だったら、テンプレートテンプレートテンプレートパラメータも……あります。

template< 
  template<
    template< class > class
   > class Type >
struct something;

テンプレート引数を1つ取る何らかの型をテンプレート引数に1つ取る何らかの型をテンプレート引数に取る構造体です。わたしもこんがらがってきました。
ここまで来ると使う機会は来ないでしょう。

32
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
21