今天,我尝试将模板类传递给模板参数。我的模板类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;
}
不幸的是,我不想一直传递最后两个参数。那真的太写了。如何在此处使用一些默认模板参数?
您可以使用类型模板参数包(自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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句