C++ Three-Way Comparison | The Spaceship Operator `<=>` (C++20)
이 글의 핵심
The spaceship operator generates consistent `<`, `>`, `<=`, `>=`, and often `==`/`!=` when `default`ed—if you model ordering correctly.
Spaceship operator
C++20 operator<=> replaces hand-written ==, !=, <, <=, >, >= in many types.
struct Point {
int x, y;
auto operator<=>(const Point&) const = default;
};
Return types
std::strong_ordering— total order (typical arithmetic-like types)std::weak_ordering— distinct values may compare equivalent (e.g. case-insensitive string)std::partial_ordering— unordered results possible (e.g.NaN)
default comparison
Memberwise lexicographic comparison on declared members—great for simple aggregates.
Custom <=>
Implement custom ordering (e.g. sort Student by score only) and sometimes operator== separately when equality semantics differ from <=> results.
Composite comparison
Chain if (auto c = field <=> other.field; c != 0) return c; across fields.
Comparison categories
Illustrates strong_ordering::less, weak_ordering::equivalent, partial_ordering::unordered with NaN.
Pitfalls
- Custom
<=>without==whendefaultequality would be wrong—defineoperator==explicitly. - Comparing unrelated types without conversions.
defaultcomparing pointer members by address when value semantics matter.
FAQ
C++20+ feature. Performance comparable to hand-written operators—compiler can optimize aggressively.
Related posts
- Range adaptors
- Template lambda
- Concepts & constraints
Keywords
C++, spaceship operator, three-way comparison, <=>, C++20.
See also
- Range adaptors
- Concepts & constraints