Use the "spaceship" operator <=> for three-way comparisons
The three-way comparison operator (<=>
), commonly called the spaceship operator because it looks like a flying saucer in profile, is new in C++20. You may wonder, what's wrong with the existing six comparison operators? Nothing at all, and you will continue using them. The purpose of the spaceship is to provide a unified comparison operator for objects.
The common two-way comparison operators return one of two states, true
or false
, according to the result of the comparison. For example:
const int a = 7; const int b = 42; static_assert(a < b);
The a < b
expression uses the less-than comparison operator (<
) to test if a
is less than b
. The comparison operator returns true
if the condition is satisfied, or false
if not. In this case it returns true
because 7 is less than 42.
The three-way comparison works differently. It returns one of three states. The spaceship operator will return...