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

Ale*_*ph0 3 c++ templates class-template

今天我尝试将模板类传递给模板参数.我的模板类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;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,我不想一直传递最后两个参数.这真是太多了.我如何在这里使用一些默认模板参数?

son*_*yao 5

您可以使用类型模板参数包(从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
};
Run Code Online (Sandbox Code Playgroud)

然后

Map<std::string, int, std::map> t;
Run Code Online (Sandbox Code Playgroud)