关于成员和自由运营商的消歧规则

Disambiguation rule concerning member and free operators

我有一个看起来像这样的程序:

class B {};

class A 
{
    template<typename T> int operator+(const T&) const { return 1; } // Function 1
};

template<typename T, typename P> int operator+(const T&, const P&) { return 2; } // Function 2

int main()
{
    A a;
    B b;
    
    std::cout<<(a + b);

    return 0;
}

在这种情况下,函数 2 将被调用。但是当我将函数 1 修改为自由函数而不是成员函数时

template<typename T> int operator+(const A&, const T&) { return 1; } // Function 1
template<typename T, typename P> int operator+(const T&, const P&) { return 2; } // Function 2

现在将调用函数 1,即使在这两种情况下函数 1 基本相同。这背后的原因是什么? GCC 根据 ISO C++ 标准抱怨歧义,但没有说明确切原因并且无论如何编译都很好。这种情况对于运算符来说是独一无二的,因为无论它们是否是成员,都可以以相同的方式调用它们。

Now Function 1 will be called, even though in both cases Function 1 is basically identical. What's the reasoning behind this?

Partial ordering of overloaded function templates执行到select此处最佳匹配。

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

函数 1 比函数 2 更专业,因为它接受的类型更少;它只能接受 A 作为它的第一个操作数,而 Function 2 可以接受任何类型。

出于同样的原因,在第一种情况下,成员函数 1 也应该 selected;作为 clang does. This seems to be gcc's bug, see Bug 53499 and Bug 66914.