gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:07:35 26 4
gpt4 key购买 nike

以下程序打印 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com