CKTIS / C++
Operator <=> — three-way comparison
The <=> operator, called spaceship, describes an ordering relationship between values. Standard result categories distinguish less, equivalent, greater, and sometimes unordered. In a class, a defaulted definition provides lexicographical comparison of subobjects.
Version: C++23; repository compiler flag; example execution verified in isolation, production runtime not attested
Syntax
a <=> b
auto operator<=>(const T&) const = default;The built-in form of a <=> b returns a value of a standard comparison category type, not a bool. A user-defined operator<=> can return bool. Built-in integer comparisons return std::strong_ordering, while floating-point comparisons return std::partial_ordering. Include <compare>. Test a standard category result using result < 0, result == 0, or result > 0; do not treat it as an integer containing -1, 0, or 1.
std::strong_ordering describes a total order with equality; std::weak_ordering allows equivalent values that need not be substitutable in observations of comparison-salient state. std::partial_ordering additionally allows unordered, for example when comparing with NaN. In that case, all three tests < 0, == 0, and > 0 are false; simply negating one test does not establish the opposite relationship.
In a class, auto operator<=>(const T&) const = default; compares lexicographically: direct bases first, then non-static data members, in declaration order. The first result unequal to zero ends the comparison, including an unordered result. The return type reflects the weakest category among the subobjects. If a required subobject comparison is unavailable, the defaulted operator can be defined as deleted.
Overload resolution can use <=> to support <, <=, >, and >=; this does not generate four separate functions. A defaulted <=> declared inside a class also implicitly declares a defaulted operator== if the class declares no operator== of its own; != can use ==. A manually implemented <=> does not by itself provide ==.
In the example, x decides the comparison before y: 1 < 2, so a < b is true despite 9 > 0. The example targets compilation with -std=c++23. Execution was verified in an isolated environment. The sources present an evolving working draft, not a frozen C++23 text.
Examples
#include <compare>
#include <iostream>
struct Point {
int x;
int y;
auto operator<=>(const Point&) const = default;
};
int main() {
const Point a{1, 9};
const Point b{2, 0};
const auto result = a <=> b;
std::cout << std::boolalpha
<< (result < 0) << '\n'
<< (a < b) << '\n'
<< (a == b) << '\n';
}
Result
true true false
The displayed source was run unchanged in an isolated environment. Its standard output (`stdout`) matched the stated output exactly.