I know that defining certain operators in C++ lets the compiler generate other operators for a class. From what I read in this cppreference article it seems like the following holds true:
operator==
must be explicitly defined (perhaps as default) to be usable.operator!=
is generated fromoperator==
if it is not defined explicitly andoperator==
is defined.operator<=>
generates the other four relational operators (if all goes to plan, that isoperator<=>
returns a result possible to interpret by the other four and is well defined for both the original and reverse parameter orders)operator<=>
does NOT generateoperator==
even if it returnsstd::strong_ordering
which, as I understand, should return an object comparable as equal to0
if and only if the two compared objects are identical (indistinguishable). I tested this myself with the following code
#include <iostream>
class Foo
{
public:
int x;
int y;
// Lexicographic ordering but by the y member first, and by x second.
std::strong_ordering operator<=>(const Foo& other)
{
if (std::strong_ordering cmp = y <=> other.y; cmp != 0)
return cmp;
return x <=> other.x;
}
};
int main()
{
Foo f = {1, 1}, g = {1, 0};
std::cout << (f == g);
}
which returns error no match for ‘operator==’ (operand types are ‘Foo’ and ‘Foo’)
.
What I want to know is, first of all, WHY DOESN'T operator<=>
generate operator==
and secondly -- is there a complete list of which operators generate other operators (and which ones), or is that cppreference article complete in that regard and there are no other operators being generated? For instance I'd expect operator+(Foo)
and operator-()
to generate operator-(Foo)
, on the basis that subtracting is nothing but adding the additive inverse. This, however, turns out to be untrue, which I also tested.