san216
san216

Reputation: 95

Overload resolution through return type?

Function overload resolution doesn't take return type into account, however I came across a piece of code on cppreference

SFINAE aside, how is overload resolution happening here:

#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)
}

I have checked. This code works. So, is trailing return type being used for overload resolution here?

Upvotes: 0

Views: 91

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96579

overload resolution doesn't take return type into account

They mean that given several viable overloads, they are not disambiguated based on the return type (on whether it matches how the return value is used, and so on).

On the other hand, when an overload is rejected due to a SFINAE-caught error, it doesn't matter if the error is in the return type or elsewhere.

Upvotes: 3

Related Questions