C ++ 20比较:关于歧义反向运算符的警告 [英] C++20 comparison: warning about ambiguous reversed operator
问题描述
考虑这个有效的C ++ 17示例:
Consider this valid C++17 example:
struct A {
bool operator==(const A&);
};
int main() {
return A{} == A{};
}
用-std = c ++ 20用clang编译时,它会给出:
<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不允许使用典型的比较运算符比较两个相同类型的对象?正确的选择是什么?将来的草稿中情况会有所改变吗?
Does this warning mean that C++20 disallows using a typical comparison operator to compare two objects of the same type? What is the correct alternative? Is the situation expected to change in future drafts?
推荐答案
此警告是否表示C ++ 20不允许使用典型的比较运算符比较两个相同类型的对象?正确的选择是什么?将来的草稿中情况会有所改变吗?
Does this warning mean that C++20 disallows using a typical comparison operator to compare two objects of the same type? What is the correct alternative? Is the situation expected to change in future drafts?
这实际上不是典型的比较运算符,它已经有点不对了-因为它只允许在一侧上 const
对象(您的 A
类型不会即使没有任何语言变化,也可以满足新的 equality_comparable
概念.
This isn't really a typical comparison operator, it's already kind of wrong - since it only allows a const
object on one side (your type A
wouldn't satisfy the new equality_comparable
concept either, even without any langauge changes).
您必须这样写:
struct A {
bool operator==(const A&) const;
// ^^^^^^
};
这是C ++ 20的最终规则.
This is the final rule for C++20.
具体问题是在C ++ 20中,比较运算符添加了新的概念,即重写和反转的候选对象.因此,对表达式 a == b
的查找也将最终匹配像 b == a
这样的运算符.在典型情况下,这意味着您必须编写更少的运算符,因为我们知道相等是可交换的.
The specific issue is that in C++20, comparison operators add a new notion of rewritten and reversed candidates. So lookup for the expression a == b
will also end up matching operators like b == a
. In the typical case, this means you have to write fewer operators, since we know equality is commutative.
但是,如果您存在const不匹配的情况,那么您将遇到以下两个候选对象:
But if you have a const-mismatch, what happens is you end up with these two candidates:
bool operator==(/* this*/ A&, A const&); // member function
bool operator==(A const&, /* this*/ A&); // reversed member function
带有两个类型为 A
的参数.第一个参数在第一个参数上更好,第二个参数在第二个参数上更好.哪一个候选人都不比另一个更好,因此模棱两可.
With two arguments of type A
. The first candidate is better in the first argument, and the second candidate is better in the second argument. Neither candidate is better than the other, hence ambiguous.
这篇关于C ++ 20比较:关于歧义反向运算符的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!