The Spaceship Operator and Expression Rewriting

A guide to simplifying our comparison operators using C++20 features
This lesson is part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, Unlimited Access
Abstract art representing computer programming
Ryan McCombe
Ryan McCombe
Updated

Let's imagine we have the following custom type, which simply stores a value, and implements an == operator:

class Number {
public:
  bool operator==(const Number& Other) const {
    std::cout << "Hello from the == operator\n";
    return Value == Other.Value;
  }

  int Value;
};

We create two objects of this type, and compare them using the != operator:

int main(){
  Number A{1};
  Number B{2};

  if (A != B) { std::cout << "Not equal!"; }
}

Our type doesn’t have the != operator, so we’d expect this to fail. In C++17 and earlier, that’s exactly what happens:

error: binary '!=': 'Number' does not define this operator

But, from C++20 onwards, this program will compile, and run as we expect:

Hello from the == operator
Not equal!

This works because, behind the scenes, the compiler has rewritten our expression.

Expression Rewriting

As the previous output would indicate, the expression using the != operator is calling the == operator of our class.

This is an example of expression rewriting, which was added to comparison operators in C++20

Specifically, if our type doesn't have the != operator, the compiler can rewrite any expression using it in terms of the == operator. So, A != B will be rewritten as !(A == B)

Specifically, any expression using a secondary comparison operator can be rewritten in terms of the corresponding primary comparison operator.

  • The secondary comparison operator != corresponds to the primary comparison operator ==
  • The secondary comparison operators !=, <, <=, > and >= correspond to the primary comparison operator <=>, which we’ll cover next

The <=> Operator

To support expression rewriting, the three-way comparison operator was added in C++20 and uses the syntax <=>:

A <=> B

Because of its visual appearance, it is often called the Spaceship Operator

The <=> operator accepts two operands, and returns one of three possible values. The return value depends on whether the left operand is less than, equal to, or greater than the right operand.

These three possibilities are contained within the std::strong_ordering struct:

  • If A < B it returns std::strong_ordering::less
  • If A == B it returns std::strong_ordering::equal
  • If A > B it returns std::strong_ordering::greater

Equivalence vs Equality

There is a fourth possible result of comparison - std::strong_ordering::equivalent. In the vast majority of cases, there is no difference between equality and equivalence. For boolean operations, they are the same thing.

However, there may be some niche cases where we want to differentiate two "levels" of equality. For example:

  • we may want to define two operands of our custom type to be equal only if they are the same object (i.e., same memory address), but still equivalent if they’re different objects with the same value
  • if we’re creating a string-like type, we may want to consider two objects equal if they’re an exact match, but still equivalent if they match on a case-insensitive basis

In code, we could use the <=> operator and std::strong_ordering type like this:

if (A <=> B == std::strong_ordering::less) {
  std::cout << "A is less than B";
}

if (A <=> B == std::strong_ordering::equal) {
  std::cout << "A is equal to B";
}

if (A <=> B == std::strong_ordering::greater) {
  std::cout << "A is greater than B";
}

The previous example shows the mechanics of the <=> operator and the std::strong_ordering type, but it’s quite unusual that we’d use them like this. The <=> syntax and std::strong_ordering reference will typically only be used in one place - in our class code, to define the three-way comparison operation.

Any other code seeking to compare our objects will still use the regular comparison operators, like > and >=, to return booleans.

The key point is that, as of C++20, these operators no longer need to be defined. The compiler can rewrite any expression that attempts to use them to secretly call the <=> operator instead

Below, our class only defines the <=> operator, but because of expression rewriting, code using our class can use regular comparison operators, like < and >=:

#include <iostream>

class Number {
public:
  // Our class defines the <=> operator
  // which returns a strong_ordering...
  std::strong_ordering operator<=>(
    const Number& Other) const{
    std::cout << "Hello from <=>\n";
    return Value <=> Other.Value;
  }

  int Value;
};

int main(){
  Number A{1};
  Number B{2};

  // ...but our consumers use the normal
  // comparison operators to return booleans
  if (A < B) { std::cout << "A < B\n"; }
  if (A <= B) { std::cout << "A <= B\n"; }
}
Hello from <=>
A < B
Hello from <=>
A <= B

In summary, starting with C++20, we now only need to define the two primary comparison operators for our types: == and <=>. All of the secondary comparison operators can be automatically generated from these.

Why can’t == and != be rewritten in terms of <=>?

It seems that any expression using the == and != operators could also be rewritten in terms of the spaceship operator <=>, so why do we need to define the == operator?

Expressions using == and != could indeed be rewritten in terms of <=>, but it’s not done automatically as this can degrade performance. Determining whether two objects are equal is usually easier, and therefore more performant, than determining their relative ordering.

In other words, operator== is usually faster than operator<=>.

For example, if string A and string B have different lengths, an == operator could immediately return false. However, an <=> operator would need to perform additional unnecessary work to determine if it should return strong_ordering::less or strong_ordering::greater.

So, if we attempt to use a == operator with a type that only implements <=>, C++ won’t rewrite our expression in a way that could be slower than it should be. Especially as we might not notice that’s what is happening - we might just assume the type has a == operator defined.

So instead, the compiler tells us the operator doesn’t exist. We can then define it, and we can even define it in terms of the <=> operator if that’s what we want:

bool operator==(const T& A, const T& B){
  return A <=> B == std::strong_ordering::equal;
}

Summary

In this lesson, we explored the power of C++20's spaceship operator (<=>) and expression rewriting, showcasing how these features make it easier to implement comparison operators for custom types.

Key Takeaways

  • Through the use of these C++20 features, only two primary comparison operators need to be defined (== and <=>).
  • The spaceship operator (<=>) enables three-way comparisons, returning one of three possible outcomes: less, equal, or greater.
  • Expression rewriting allows the compiler to automatically generate secondary comparison operators (!=, <, <=, >, >=) from the primary comparison operators (==, <=>).
  • std::strong_ordering is used with the spaceship operator to define the outcome of comparisons.
  • An explicit definition of == is necessary alongside <=> to improve our type’s runtime performance.

Was this lesson useful?

Next Lesson

C++20 Modules

A detailed overview of C++20 modules - the modern alternative to #include directives. We cover import and export statements, partitions, submodules, how to integrate modules with legacy code, and more.
Abstract art representing computer programming
Ryan McCombe
Ryan McCombe
Updated
Lesson Contents

The Spaceship Operator and Expression Rewriting

A guide to simplifying our comparison operators using C++20 features

A computer programmer
This lesson is part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, Unlimited Access
A computer programmer
This lesson is part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Next Lesson

C++20 Modules

A detailed overview of C++20 modules - the modern alternative to #include directives. We cover import and export statements, partitions, submodules, how to integrate modules with legacy code, and more.
Abstract art representing computer programming
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved