C++20 adds a feature allowing the language to do something like this for relational (<
, >
, <=
, >=
) and equality operators (==
and !=
).
When using equality operators, the system can attempt to reverse the order of the operands (for equality testing of different types) as well as negate the result in order to find an appropriate operator==
overload. That is, if you only implement operator==
for equality testing A
with B
, this will also allow you to equality test B
with A
, and inequality test them as well.
Note that the compiler is not generating operator functions for you. It is instead modifying the actual place where it is invoking the operator. That is, it turns b != a
into !(a == b)
in order to find an appropriate ==
operator.
For <=>
, it gets applied to all of the relational operators (but not the equality operators) in much the same way. The system will rewrite a < b
to be (a <=> b) < 0
or (b <=> a) > 0
as needed to find a matching overloaded <=>
operator.
Additionally, you can = default
any of the comparison operators, which does a subobject-wise, in order comparison of the subobjects of the type in question (you can only default comparisons of the same type). If you default the ==
operator, then per the above rules, you effectively get !=
as well. If you default <=>
, you get all of the relational operators via rewriting.
If you default <=>
without defaulting ==
, then the system will also generate a default ==
, so defaulting <=>
alone gives you all of the comparison operators.
operator++()
tooperator++(int)
as well, I feel like you should only have to give one of those. – Keavy