Operators, Overloading & Spaceship Operator (<=> in C++20)
1Concept
C++ allows user-defined operator overloading. C++20 introduced the Three-Way Comparison (Spaceship) operator <=>, which allows the compiler to auto-generate all 6 relational operators (==, !=, <, <=, >, >=) with default ordering.
2Architecture Diagram
a <=> b: Returns: - std::strong_ordering::less (if a < b) - std::strong_ordering::equal (if a == b) - std::strong_ordering::greater (if a > b)
3Code Example
Stage 0 Language Foundations
#include <iostream>
#include <compare>
struct Point {
int x;
int y;
// C++20 spaceship operator auto-generates ==, !=, <, <=, >, >=
auto operator<=>(const Point&) const = default;
};
int main() {
Point p1{10, 20};
Point p2{10, 30};
Point p3{10, 20};
std::cout << std::boolalpha;
std::cout << "p1 == p3: " << (p1 == p3) << "\n";
std::cout << "p1 < p2: " << (p1 < p2) << "\n";
std::cout << "p2 > p1: " << (p2 > p1) << "\n";
return 0;
}4Expected Output
p1 == p3: true p1 < p2: true p2 > p1: true
5Key Takeaways
- ✓C++20 auto operator<=>(const T&) const = default generates complete ordering comparisons.
- ✓Operator overloading should follow natural mathematical semantics.
- ✓Logical operators && and || short-circuit; overloaded && does not short-circuit.