How do I use three-way comparison (<=>) in C++20?

C++20 introduces the three-way comparison operator, also known as the spaceship operator (<=>). This operator allows for a single, concise way to compare two objects in terms of their order, making it easier to implement comparison logic.

To use the three-way comparison operator, you simply need to implement the operator in your class and use it in place of traditional comparison operators such as <, >, ==, etc. Here's a simple example:

#include #include struct Point { int x, y; auto operator<=> (const Point& other) const = default; }; int main() { Point p1{1, 2}; Point p2{2, 3}; if (p1 < p2) { std::cout << "p1 is less than p2" << std::endl; } else { std::cout << "p1 is not less than p2" << std::endl; } return 0; }

C++20 three-way comparison spaceship operator &lt;=&gt; operator C++ comparison operators