我有一个看起来像这样的程序:
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 基本相同。这背后的原因是什么?根据 ISO C++ 标准,GCC 提示歧义,但没有说明确切原因并且无论如何编译都很好。这种情况对于运算符(operator)来说是独一无二的,因为无论他们是否是成员,都可以以相同的方式调用它们。
最佳答案
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执行以在此处选择最佳匹配。
Informally "A is more specialized than B" means "A accepts fewer types than B".
函数 1 比函数 2 更专业,因为它接受的类型更少;它只能接受
A
作为它的第一个操作数,而函数 2 可以接受任何类型。出于同样的原因,在第一种情况下也应该选择成员函数 1;如 clang做。这似乎是gcc的bug,见Bug 53499和 Bug 66914 .
关于c++ - 关于成员和自由运算符的消歧规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63445225/