2016-07-07 186 views
3

今天我试着将模板类传递给模板参数。我的模板类std::map有四个模板参数,但最后两个是默认参数。模板类作为模板参数默认参数

我能得到下面的代码进行编译:

#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

你可以使用type template parameter pack(因为C++ 11),以允许可变参数模板参数:

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