首页 > 解决方案 > 这是什么构造:模板无效函数名称(int i)?

问题描述

我在编写模板函数特化时不小心犯了一个错误,结果构造通过了 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-specializationfunction-templates

解决方案


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

你可以这样称呼它:

tempfunc<42>(42);

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

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

这是一个演示


推荐阅读