Member-only story

Introduction to the C++20 spaceship operator

CMP
7 min readAug 28, 2023

C++20 introduced the three-way comparison operator, also known as the “spaceship operator” due to its appearance: <=>. The purpose is to streamline the process of comparing objects.

The Basics

Below is a simple example that uses this new spaceship operator:

#include <compare>

int main() {
int a = 1;
int b = 2;

auto result = a <=> b;

if (result < 0) {
std::cout << "a is less than b" << std::endl;
} else if (result == 0) {
std::cout << "a is equal to b" << std::endl;
} else { // result > 0
std::cout << "a is greater than b" << std::endl;
}

return 0;
}

Note that the compare header must be included.

For integral types such as int, the type of the value returned by the spaceship operator is std::strong_ordering, which can have one of three values:

  • std::strong_ordering::less: If the left operand (a) is less than the right operand (b).
  • std::strong_ordering::equal: If a is equal to b.
  • std::strong_ordering::greater: If a is greater than b.

For floating-point types such as double, the spaceship operator returns one of four possible values:

  • std::partial_ordering::less: If a is less than b.
  • std::partial_ordering::equivalent: If a is “equivalent” to b. This is essentially the same as “equal”, but also includes the case of -0 <=> +0.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

CMP
CMP

Written by CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.

Responses (3)

Write a response

TIL something new. Ty for the clear explanation

#include <algorithm>
#include <iostream>
#include <vector>
class TypeB {
public:
int a = 10;
TypeB() {}
TypeB(int _a) : a{_a} {}
};
class TypeA {
public:
float a = 10.0f;
TypeA() {}
TypeA(float _a) : a{_a} {}
bool operator==(const TypeB& b) const {
std::cout <<…

I watched couple of video's to understand spaceship operator but didn't get clear picture. I thought this article might be helpful, but unfortunately it is only available for members only :). That's ok, I will learn and publish article.