简体   繁体   English

模板类作为模板参数的默认参数

[英]Template class as template parameter default parameter

Today I tried to pass a template class to a template parameter. 今天我尝试将模板类传递给模板参数。 My template class std::map has four template parameters, but the last two of them are default parameters. 我的模板类std::map有四个模板参数,但最后两个是默认参数。

I was able to get the following code to compile: 我能够得到以下代码来编译:

#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;
}

Unfortunately, I don't want to pass the last two parameters all the time. 不幸的是,我不想一直传递最后两个参数。 That is really too much writing. 这真是太多了。 How can I use here some default template arguments? 我如何在这里使用一些默认模板参数?

You could use type template parameter pack (since C++11) to allow variadic template parameters: 您可以使用类型模板参数包 (从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
};

then 然后

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

Not ideal, but: 不理想,但是:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM