Consider this valid C++17 example:
struct A {
bool operator==(const A&);
};
int main() {
return A{} == A{};
}
When 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&);
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?
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?
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).
You have to write it this way:
struct A {
bool operator==(const A&) const;
// ^^^^^^
};
This is the final rule for C++20.
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.
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
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.