Skip to content

Three-Way Comparison Operator <=> (C++20) ​

In a Nutshell ​

Define operator<=> once, and the compiler automatically generates all six comparison operators — <, <=, >, >=, ==, and !=. Say goodbye to hand-written comparison code.

#include <compare> (when using the predefined comparison categories)

Core API Cheat Sheet ​

OperationSignatureDescription
Three-way comparisonauto operator<=>(const T&) const = default;The compiler generates the comparison logic automatically
Hand-written three-way comparisonstd::strong_ordering operator<=>(const T& rhs) const;Custom comparison semantics
Strong orderingstd::strong_orderingEquivalent elements are indistinguishable (e.g., int)
Weak orderingstd::weak_orderingEquivalent elements are distinguishable but compare equal (e.g., case-insensitive strings)
Partial orderingstd::partial_orderingIncomparable cases exist (e.g., NaN)
Equality operatorbool operator==(const T&) const = default;Defaulting this alone also auto-generates !=

Minimal Example ​

C++
// Standard: C++20
#include <compare>
#include <iostream>

struct Point {
    int x, y;
    auto operator<=>(const Point&) const = default;
};

int main() {
    Point a{1, 2}, b{1, 3};
    std::cout << (a < b)  << "\n"; // true  (auto-generated)
    std::cout << (a == b) << "\n"; // false (auto-generated)
    std::cout << (a != b) << "\n"; // true  (auto-generated)

    auto cmp = a <=> b;
    std::cout << (cmp < 0) << "\n"; // true (strong_ordering::less)
}

Embedded Suitability: Medium ​

  • Compile-time feature with zero runtime overhead — the defaulted comparison code is equivalent to hand-written code
  • Well suited to structs that need lexicographical comparison, such as sensor data or protocol headers
  • Requires C++20 support (GCC 10+); some embedded toolchains are not fully there yet
  • Comparison categories (strong/weak/partial) are fairly abstract concepts; the team needs a shared understanding

Compiler Support ​

GCCClangMSVC
101019.20

See Also ​


Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05