Skip to content

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

In a Nutshell

Define operator<=> and the compiler auto-generates all six comparison operators (<, <=, >, >=, ==, !=) — goodbye boilerplate comparison code.

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

Core API Quick Reference

OperationSignatureDescription
Three-way comparisonauto operator<=>(const T&) const = default;Compiler auto-generates comparison logic
Custom three-waystd::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 values exist (e.g., NaN)
Equality operatorbool operator==(const T&) const = default;Defaulting == alone auto-generates !=

Minimal Example

cpp
// 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 Applicability: Medium

  • Compile-time feature with zero runtime overhead — default-generated comparisons are equivalent to hand-written code
  • Suitable for structs requiring lexicographic comparison (sensor data, protocol headers)
  • Requires C++20 support (GCC 10+); some embedded toolchains are not yet fully ready
  • Comparison categories (strong/weak/partial) are conceptually abstract; teams need shared understanding

Compiler Support

GCCClangMSVC
101019.20

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress