正常
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.
Header
#include <compare> (when using the predefined comparison categories)
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Three-way comparison | auto operator<=>(const T&) const = default; | The compiler generates the comparison logic automatically |
| Hand-written three-way comparison | std::strong_ordering operator<=>(const T& rhs) const; | Custom comparison semantics |
| Strong ordering | std::strong_ordering | Equivalent elements are indistinguishable (e.g., int) |
| Weak ordering | std::weak_ordering | Equivalent elements are distinguishable but compare equal (e.g., case-insensitive strings) |
| Partial ordering | std::partial_ordering | Incomparable cases exist (e.g., NaN) |
| Equality operator | bool 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
| GCC | Clang | MSVC |
|---|---|---|
| 10 | 10 | 19.20 |
See Also
Part of the content is referenced from cppreference.com and is licensed under CC-BY-SA 4.0