这是什么构造:template <int> void funcName(int i)?

Gon*_*n I 2 c++ template-specialization function-templates

我不小心在编写模板函数专业化时犯了一个错误,结果构造通过了 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";
}
Run Code Online (Sandbox Code Playgroud)

我无法调用第三个构造。

cig*_*ien 6

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

你可以这样称呼它:

tempfunc<42>(42);
Run Code Online (Sandbox Code Playgroud)

请注意,不使用模板语法的调用仍将调用在类型参数上模板化的版本:

tempfunc(42);   // calls specialization
tempfunc(true); // calls primary 
Run Code Online (Sandbox Code Playgroud)

这是一个演示