考虑以下有效的C++ 17示例:
struct A {
bool operator==(const A&);
};
int main() {
return A{} == A{};
}
当compiled in clang with -std=c++20 it gives时:
<source>:7:15: warning: ISO C++20 considers use of overloaded operator '==' (with operand types 'A' and 'A') to be ambiguous despite there being a unique best viable function [-Wambiguous-reversed-operator]
return A{} == A{};
~~~ ^ ~~~
<source>:2:9: note: ambiguity is between a regular call to this operator and a call with the argument order reversed
bool operator==(const A&);
此警告是否表示C++ 20不允许使用典型的比较运算符比较两个相同类型的对象?正确的选择是什么?将来的草稿中情况会有所改变吗?
最佳答案
这实际上不是典型的比较运算符,它已经有点不对了-因为它只允许一侧上的const
对象(即使不进行任何语言更改,您的A
类型也不满足新的equality_comparable
概念)。
您必须这样写:
struct A {
bool operator==(const A&) const;
// ^^^^^^
};
这是C++ 20的最终规则。
特定的问题是在C++ 20中,比较运算符添加了新的概念,即重写和逆向候选。因此,查找表达式
a == b
还将最终匹配匹配运算符,例如b == a
。在典型情况下,这意味着您必须编写更少的运算符,因为我们知道相等是可交换的。但是,如果您存在const不匹配的情况,那么您将遇到以下两个候选对象:
bool operator==(/* this*/ A&, A const&); // member function
bool operator==(A const&, /* this*/ A&); // reversed member function
具有
A
类型的两个参数。第一个参数在第一个参数上更好,第二个参数在第二个参数上更好。哪一个候选人都不比另一个更好,因此模棱两可。关于c++ - C++ 20比较: warning about ambiguous reversed operator,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60386792/