【问题标题】:Why cannot a template template parameter be defaulted?为什么不能默认模板模板参数?
【发布时间】:2017-03-15 12:44:00
【问题描述】:
#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

【问题讨论】:

  • 如果您阅读错误消息,它会说“模板模板参数必须是类模板”。 std::basic_string 本身一个类模板。 std::basic_string &lt;CharType, std::char_traits&lt;CharType&gt;, std::allocator&lt;CharType&gt;&gt; 不是模板,它是从std::basic_string 模板派生的具体类。

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


【解决方案1】:

试试

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

【讨论】:

  • 这仅适用于像 STL 这样的StringType 实现。不适用于例如const CharType*
  • @virgesmith - 抱歉,我不明白你的意思;拜托,请您准备一个示例并作为问题发布吗?
  • 您已经强加 StringType 是一个需要 3 个参数的模板,例如f 无法实例化。请参阅下面的答案。
  • @virgesmith - 哦,是的;我强加了三个参数,因为 OP 强加了三个参数;如果你想要一个带有未定义参数数量的模板模板参数,你可以写template&lt;typename...&gt; class StringType = std::basic_string
【解决方案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
}

【讨论】:

    猜你喜欢
    • 2011-10-01
    • 2016-11-09
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2012-08-07
    • 2017-04-15
    • 2020-03-30
    • 2018-07-16
    相关资源
    最近更新 更多