2016-07-07 8 views
3

今日、私はテンプレートクラスにテンプレートクラスを渡そうとしました。私のテンプレートクラスstd::mapには4つのテンプレートパラメータがありますが、最後の2つはデフォルトパラメータです。テンプレートパラメータとしてのテンプレートクラスのデフォルトパラメータ

#include <map> 

template<typename K, typename V, typename P, typename A, 
    template<typename Key, typename Value, typename Pr= P, typename All=A> typename C> 
struct Map 
{ 
    C<K,V,P,A> key; 
}; 

int main(int argc, char**args) { 
    // That is so annoying!!! 
    Map<std::string, int, std::less<std::string>, std::map<std::string, int>::allocator_type, std::map> t; 
    return 0; 
} 

残念ながら、私は最後の二つのパラメータのすべての時間を渡すためにしたくない:

私はコンパイルするには、次のコードを取得することができました。それは本当にあまりにも多くの書き込みです。ここで、デフォルトのテンプレート引数をいくつか使用できますか?

答えて

5

あなたは可変長テンプレートパラメータ許可する(C++ 11以降)type template parameter packを使用することができます。

template<typename K, typename V, 
    template<typename Key, typename Value, typename ...> typename C> 
struct Map 
{ 
    C<K,V> key; // the default value of template parameter Compare and Allocator of std::map will be used when C is specified as std::map 
}; 

その後、

Map<std::string, int, std::map> t; 
+0

感謝を!私はこれらの新しいバリデーショナルテンプレートを認識していませんでした。エレガントで短い。 – Aleph0

3

理想的な、しかしない:

#include <map> 

template<typename K, typename V, typename P, 
    typename A=typename std::map<K, V, P>::allocator_type, 
    template<typename Key, typename Value, typename Pr= P, typename All=A> typename C=std::map> 
struct Map 
{ 
    C<K,V,P,A> key; 
}; 

int main(int argc, char**args) { 
    Map<std::string, int, std::less<std::string>> t; 
    return 0; 
} 
+0

ユーザが 'std :: less 'を置き換える必要がある場合には、それほど悪くありません。 – Aleph0

関連する問題