c++ - 模板重载解析: what happens when multiple templates match?

标签 c++ templates overload-resolution

以下程序打印 T,T

#include <iostream>

template<typename T>
void f(T x, T y) {
  std::cout << "T,T\n";
}

template<typename T1, typename T2> 
void f(T1 x, T2 y) {
  std::cout << "T1,T2\n";
}

int main() {
  f(1, 1); 
  return 0;
}

代码中哪个模板排在前面并没有什么区别。

我希望重载解析在这里是不明确的。 TT1T2 都应该被推导为 int,这使得两个模板与调用站点完全匹配.

我无法找到任何解析规则 ( https://en.cppreference.com/w/cpp/language/overload_resolution ) 来解释为什么它会选择第一个模板。

我使用 clang++ -std=c++17 进行了测试,以防万一。

最佳答案

overloaded function templates 的部分排序执行以确定应选择哪一个。

When the same function template specialization matches more than one overloaded function template (this often results from template argument deduction), partial ordering of overloaded function templates is performed to select the best match.

Specifically, partial ordering takes place in the following situations:

1) overload resolution for a call to a function template specialization

template<class X> void f(X a);
template<class X> void f(X* a);
int* p;
f(p);

2) ...

...

Informally "A is more specialized than B" means "A accepts fewer types than B".

选择第一个重载是因为它只接受一种相同类型的参数,而第二个重载可以接受两种独立类型的参数。

关于c++ - 模板重载解析: what happens when multiple templates match?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128987/

相关文章:

c++ - 作为模板参数的结构数组

c++ - C++14 中的依赖限定名查找

c++ - 为什么编译器不能决定在没有引用运算符的情况下调用哪个函数?

c++ - 我怎样才能为一个概念重载一个函数?

c++ - 函数 C++ 中具有大小返回类型的模板?

c++ - 当以有序方式添加项目时,二叉搜索树有效地充当链表

c++ - delete[] 是否适用于通用数组?如果是这样,为什么在其上使用 std::vector::erase 会导致释放内存时出错

c++ - 为什么 C++ 在定义点禁止非整型数据成员初始化?

c++ - 模板滥用?

javascript - 下划线模板 - 更改标记标记