【问题标题】:Template class as template parameter default parameter模板类作为模板参数默认参数
【发布时间】:2016-11-09 15:33:35
【问题描述】:

今天我尝试将模板类传递给模板参数。我的模板类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++ templates class-template


    【解决方案1】:

    您可以使用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;
    

    【讨论】:

    • 非常感谢!我不知道这些新的可变参数模板。优雅而简短。
    【解决方案2】:

    不理想,但是:

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

    【讨论】:

    • 还不错,以防用户需要替换std::less&lt;std::string&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    相关资源
    最近更新 更多