C++20 introduces the "spaceship" operator<=>
that replaces all the other comparison operators in most cases. When this operator
is defined, the compiler can rewrite expressions using <
, <=
, >
and >=
to use this
operator instead. This presents three advantages:
- Less code to write (and therefore fewer bugs, too),
- Guaranteed consistency between all the comparison operators (for instance, in this situation,
a < b
and !(a >=
b)
will always return the same value).
- Guaranteed symmetry for comparisons: if you can write
a < b
, and that operation is resolved through
operator<=>
, you can also write b < a
, and get a consistent result. Achieving the same result with classical
comparison operators requires twice as many overloads if a
and b
have different types.
Additionally, if the operator<=>
has the defaulted implementation, the compiler can implicitly generate a defaulted
implementation of operator==
, simplifying the class definition one step further.
Before C++20, it was common to provide only operator<
for a class and ask the users of this class to write all their code only
using this operator (this is what std::map
requires of its key type, for instance). In this case, it is still advised to replace the
operator with <=>
: the quantity of required work is similar, and users of the class will benefit from a much greater
expressivity.