I was going through this guide on operator overloading in C++.
If I try to implement all the comparison operators using the <=>
operator:
friend auto operator<=>(const Some_class& lhs, const Some_class& rhs)
{
if (lhs.x < rhs.x) return std::strong_ordering::less;
if (lhs.x > rhs.x) return std::strong_ordering::greater;
else return std::strong_ordering::equal;
}
The ==
operator wont the defined for Some_class
. So I additionally have to implement:
friend bool operator==(const Some_class& lhs, const Some_class& rhs)
{
if (lhs.x == rhs.x) return true;
return false;
}
The guide does state that this is necessary:
In C++20, if a comparison isn’t directly implemented, the compiler
will also try to use rewrite candidates. Thanks to this, even if <=>
isn’t defaulted (which would implement all operators), we only have to
implement == and <=>, and all other comparisons are rewritten in terms
of these two.
But I don’t get why. Why is not the first code snippet enough for the compiler to define the ==
operator?
Note: I can not default <=>
in this case.