Learning Hub Search Ctrl K

Modern C++ › C++20

Three-way Comparison (<=>)

The spaceship operator and defaulted comparisons.

Since C++20 intermediate #spaceship#three-way-comparison#defaulted-comparison#strong_ordering#partial_ordering

Explanation

The three-way comparison operator <=> (“spaceship”) returns an object that says whether the left side is less, equal or greater. The compiler rewrites all six relational operators in terms of it: a < b becomes (a <=> b) < 0.

The result types (header <compare>) describe how strict the ordering is:

Type Meaning Example
std::strong_ordering equal values are indistinguishable int, std::string
std::weak_ordering equivalent but distinguishable case-insensitive strings
std::partial_ordering some values are unordered double (NaN)

The biggest win: = default. auto operator<=>(const T&) const = default; compares all members in declaration order and also gives you == and !=. Declaring operator== as defaulted is implied when <=> is defaulted.

Also: a == b uses operator==, never <=>, so == can short-circuit (compare sizes first for containers). Mixed-type comparisons work because rewriting also swaps the operands.

Example

#include <compare>
#include <iostream>
#include <set>
#include <string>

struct Version {
    int major, minor, patch;
    auto operator<=>(const Version&) const = default;       // gives ==, !=, <, <=, >, >=
};

struct Student {
    std::string name;
    double gpa;
    // custom ordering: by gpa (higher is "greater"), then name; double => partial_ordering
    std::partial_ordering operator<=>(const Student& o) const {
        if (auto c = gpa <=> o.gpa; c != 0) return c;
        return name <=> o.name;                              // string gives strong_ordering, converts
    }
    bool operator==(const Student& o) const { return gpa == o.gpa && name == o.name; }
};

struct CaseInsensitiveWord {
    std::string text;
    std::weak_ordering operator<=>(const CaseInsensitiveWord& o) const {
        auto lower = [](std::string s) { for (auto& c : s) c = static_cast<char>(std::tolower(c)); return s; };
        return lower(text) <=> lower(o.text);
    }
    bool operator==(const CaseInsensitiveWord& o) const { return (*this <=> o) == 0; }
};

int main() {
    Version a{1, 2, 3}, b{1, 10, 0};
    std::cout << (a < b) << (a == b) << (a >= b) << "\n";          // 100

    Student s1{"Ann", 3.8}, s2{"Bob", 3.5};
    std::cout << (s1 > s2) << (s1 == s2) << "\n";                  // 10

    CaseInsensitiveWord w1{"Hello"}, w2{"hELLO"};
    std::cout << (w1 == w2) << "\n";                                // 1

    std::set<Version> releases{{2, 0, 0}, {1, 5, 1}, {1, 5, 0}};   // set only needs operator<
    std::cout << releases.begin()->minor << releases.begin()->patch << "\n";   // 50

    auto r = 1.0 <=> 2.0;                                           // std::partial_ordering
    std::cout << (r < 0) << (r == std::partial_ordering::less) << "\n";   // 11
    return 0;
}

Common pitfalls

  • Defaulted <=> compares members in declaration order; reordering the members changes the ordering.
  • A defaulted <=> is deleted if any member lacks a usable <=>/<, e.g. a raw pointer type works but a type with no comparison doesn’t.
  • For a custom <=>, remember to define operator== as well (it isn’t generated from a non-defaulted <=>).
  • Floating-point members make the whole result partial_ordering; a < b, a >= b and a == b can all be false for NaN.
  • Comparing the result with something other than a literal 0 is an error: write (a <=> b) < 0, not < 1.

Legacy vs modern

// C++98..17: six operators, easy to get one wrong
bool operator==(const V& o) const { return tie(a,b,c) == tie(o.a,o.b,o.c); }
bool operator!=(const V& o) const { return !(*this == o); }
bool operator< (const V& o) const { return tie(a,b,c) <  tie(o.a,o.b,o.c); }
bool operator> (const V& o) const { return o < *this; }
bool operator<=(const V& o) const { return !(o < *this); }
bool operator>=(const V& o) const { return !(*this < o); }
// C++20
auto operator<=>(const V&) const = default;

See Operator Overloading for the rules this simplifies.

Exercises

1. Which ordering category does comparing two doubles produce, and why?

std::partial_ordering, because NaN is neither less than, equal to, nor greater than any value (including itself).