Spaceship Operator

Introduced in C++20.

#include <compare>
 
struct Vec2 {
  int x, y;
 
  std::strong_ordering operator<=>(const Vec2& other) const {
    if (auto c = x <=> other.x; c != 0) return c;
    return y <=> other.y;
  }
 
  bool operator==(const Vec2&) const = default;
};
 

if c == 0, then it means that they are equal

Before, you had to define

  • Define equality
  • Define <

Whereas now, we can make use of the <==> operator.

We have 3 types of ordering:

  • std::strong_ordering: a true total order.
    • If a == b, they’re interchangeable for ordering purposes.
    • Integers, strings, tuples of strongly-ordered things → usually strong.
  • std::weak_ordering: still a total order, but allows “equivalent but not equal”.
    • Classic example: case-insensitive compare where "a" and "A" sort the same (equivalent) but are not equal.
    • Also used for things like comparing objects by a key that doesn’t fully determine equality.
  • std::partial_ordering: sometimes things are unordered.
    • Example: floating point because NaN is unordered w.r.t everything.