具有相同名称的不同函数模板之间的重载优先级

Overloading priority between different function templates with identical name

本文关键字:优先级 函数模板 之间 重载      更新时间:2023-10-16

很抱歉标题不清楚,如果您找到更好的标题,请随时对其进行编辑。在普通函数和模板函数之间的优先级中已经深入讨论了一个相关主题, 但我没有找到我问题的答案。

我的代码是:

template<typename T>
void f(T t){std::cout << "Template 1" << std::endl;} // template 1
template<typename T, typename B>
void f(T t){std::cout << "Template 2" << std::endl;} // template 2
int main () {
   f(1);  // line 1, template 1 will be called
   f<int>(1);  // template 1 will be called
   f<int,int>(1);  // template 2 will be called
}
在第 1

行调用模板 1 函数的可能原因是什么?规范中是否明确定义?

在第 1 行,我认为编译器应该给出一个"模棱两可的重载"错误。

无法

推断B(没有参数的类型为B),因此模板 1 是唯一可能的重载。