Search⌘ K
AI Features

Use the Spaceship Operator <=> for Three-Way Comparisons

Explore the C++20 spaceship operator to understand its role in performing three-way comparisons. Learn how it replaces multiple comparison operators with a single implementation, streamlining class comparisons and improving code clarity and efficiency.

We'll cover the following...

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 we 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 77 is less than 42 ...