为什么模板模板参数不能默认?

时间:2017-03-15 12:44:00

标签: c++ c++11 templates overloading template-templates

#include <string>

template
<
    typename CharType,
    template<class, class, class> class StringType = std::basic_string
    <CharType,  std::char_traits<CharType>, std::allocator<CharType>>
>
void f(CharType, StringType)
{}

int main()
{
    char c;
    std::string str;

    f(c, str);
    //
    // error : default template argument for
    //  a template template parameter must be a class template
    //
}

为什么template template parameter无法默认?

2 个答案:

答案 0 :(得分:4)

尝试

template
<
    typename CharType,
    template<class, class, class> class StringType = std::basic_string
>
void f(CharType, StringType<CharType, std::char_traits<CharType>,
                            std::allocator<CharType>>)
{}

std::basic_string<CharType, std::char_traits<CharType>, std::allocator<CharType>>是一个简单的类型名称;如果你想要一个template<typename, typename, typename> class,你必须扔掉模板参数并使用骨架:std::basic_string

答案 1 :(得分:2)

或者,这对StringType实现的限制较少:

#include <string>

template
<
    typename CharType,
    typename StringType = std::basic_string<CharType,std::char_traits<CharType>,std::allocator<CharType>>
>
void f(CharType, StringType)
{
}


int main()
{
    char c;
    std::string str;

    f(c, str);

    const char* cstring;

    f(c, cstring); // also works
}