Skip to content

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

In a Nutshell

Defining operator<=> allows the compiler to automatically generate <, >, <=, >=, ==, and !=. Say goodbye to writing comparison code manually.

<compare> (when using predefined comparison categories)

Core API Cheat Sheet

OperationSignatureDescription
Three-way comparisonauto operator<=>(const T&) const = default;Compiler automatically generates comparison logic
Manual three-way comparisonstd::strong_ordering operator<=>(const T&) 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 this alone automatically generates !=

Minimal Example

cpp
#include <compare>
#include <iostream>

struct Point {
    int x, y;

    // Compiler auto-generates <, <=, >, >=, ==, !=
    std::strong_ordering operator<=>(const Point&) const = default;
};

int main() {
    Point p1{1, 2}, p2{1, 5};

    if (p1 < p2) {
        std::cout << "p1 is less than p2\n";
    }
    // p1 == p1, p2 != p1 also work
}

Embedded Applicability: Medium

  • Compile-time feature, zero runtime overhead—defaulted comparison code is equivalent to handwritten code.
  • Suitable for structs requiring lexicographical comparison, such as sensor data or protocol headers.
  • Requires C++20 support (GCC 10+); some embedded toolchains are not yet fully ready.
  • Comparison categories (strong/weak/partial) are abstract concepts; teams need a unified understanding.

Compiler Support

GCCClangMSVC
101019.20

See Also


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05