Table of Contents

<compare>

<compare> provides the three-way comparison operator <=> (spaceship operator) and comparison result types (std::strong_ordering, std::weak_ordering, std::partial_ordering) introduced in C++20. It allows you to define a single operator<=> that automatically generates ==, !=, <, >, <=, >=.

Use it to reduce boilerplate when a type needs rich comparison semantics.

Example

This example uses the defaulted spaceship operator to automatically derive all comparison operators for a Point struct.

// compile: g++ -std=c++20 -o compareexample compareexample.cpp
// run: ./compareexample
// description: three-way comparison with spaceship operator
 
#include <compare>
#include <iostream>
 
struct Point {
    int x, y;
 
    auto operator<=>(const Point& other) const = default;
};
 
int main() {
    Point p1{1, 2};
    Point p2{1, 3};
 
    if (p1 < p2) {
        std::cout << "p1 < p2 (automatically derived)\n";
    }
 
    return 0;
}