【问题标题】:What is this construct : template <int> void funcName(int i)?这是什么构造:模板 <int> void funcName(int i)?
【发布时间】:2020-10-01 19:12:00
【问题描述】:

我在编写模板函数特化时不小心犯了一个错误,结果构造通过了 VS17 的编译。 (下面包含的代码中的第三个构造)

这是一个有效的构造吗? 我该如何调用这个函数?

template <class T> void tempfunc(T t)
{
    cout << "Generic Template Version\n";
}

template <>
void tempfunc<int>(int i) {
    cout << "Template Specialization Version\n";
}

template <int> void tempfunc(int i)
{
    cout << "Coding Mistake Version\n";
}

我无法调用第三个构造。

【问题讨论】:

    标签: c++ template-specialization function-templates


    【解决方案1】:

    是的,这是一个有效的构造。这是一个模板重载,它在int 类型的非类型模板参数上进行模板化。

    你可以这样称呼它:

    tempfunc<42>(42);
    

    请注意,没有模板语法的调用仍然会调用在类型参数上模板化的版本:

    tempfunc(42);   // calls specialization
    tempfunc(true); // calls primary 
    

    这是demo

    【讨论】:

    • @cigien 感谢您的解释。虽然我熟悉非类型模板参数,但我认为我没有见过省略参数名称的示例。
    • @GonenI:我也从来没有。我正在努力思考它的用途
    • @MooingDuck 就在这里:stackoverflow.com/questions/59824884/…
    【解决方案2】:

    template参数有两种——类型参数和非类型参数。

    当你使用

    template <class T> void tempfunc(T t) { ... }
    

    template 参数是一个类型参数。要使用这样的模板,必须推导或显式提供类型。

    当你使用

    template <int> void tempfunc(int i) { ... }
    

    template 参数是非类型参数。据我所知,无法推断出非类型参数的值。必须明确提供。

    最后一个template 使用非类型参数。可以调用它的值必须是int 类型。示例调用:

    tempfunc<0>(20);
    tempfunc<999>(34);
    

    【讨论】:

    • 称为“非类型模板参数”
    猜你喜欢
    • 2011-04-12
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 2020-09-16
    相关资源
    最近更新 更多