函数重载解析不考虑返回类型,但是我在Cppreference
上遇到了一段代码SFINAE 不谈,这里的重载解析是如何发生的:
#include <iostream>
// This overload is added to the set of overloads if C is
// a class or reference-to-class type and F is a pointer to member function of C
template<class C, class F>
auto test(C c, F f) -> decltype((void)(c.*f)(), void())
{
std::cout << "(1) Class/class reference overload called\n";
}
// This overload is added to the set of overloads if C is a
// pointer-to-class type and F is a pointer to member function of C
template<class C, class F>
auto test(C c, F f) -> decltype((void)((c->*f)()), void())
{
std::cout << "(2) Pointer overload called\n";
}
// This overload is always in the set of overloads: ellipsis
// parameter has the lowest ranking for overload resolution
void test(...)
{
std::cout << "(3) Catch-all overload called\n";
}
int main()
{
struct X { void f() {} };
X x;
X& rx = x;
test(x, &X::f); // (1)
test(rx, &X::f); // (1), creates a copy of x
test(&x, &X::f); // (2)
test(42, 1337); // (3)
}
我已经查过了。这段代码有效。那么,这里是否使用尾随返回类型来进行重载解析?
重载解析不考虑返回类型
它们意味着,给定几个可行的重载,它们不会根据返回类型(是否与返回值的使用方式匹配,等等)消除歧义。
另一方面,当重载由于 SFINAE 错误而被拒绝时,错误是在返回类型中还是在其他地方并不重要。