In C++20, what does auto operator<=>(const Money&) const = default generate for a Money class, and what type does it return?
answer
- one operator, four relations
- lexicographic, declaration order
- the weakest member category
- an == comes with it
basics
~20 sIt compares bases and then members in declaration order, lexicographically, and returns the common comparison category of the members: std::strong_ordering for integers, std::partial_ordering once a double is involved. It also implicitly declares a defaulted ==.
solid answer
~50 sA defaulted `operator<=>` (C++20, header `<compare>`) compares the base classes and then the non-static data members **in declaration order** and returns the first result that is not equal, which is a **lexicographic** comparison. With `auto` as the return type, the result type is the **common comparison category** of the members' own `<=>`: `std::strong_ordering` if every member gives it (all integers, `std::string`), `std::weak_ordering` if any gives weak, and `std::partial_ordering` if any gives partial, as `double` does because of NaN. The compiler then **rewrites** `a < b` as `(a <=> b) < 0`, and likewise `>`, `<=` and `>=`. If the class declares no `operator==` of its own, defaulting `<=>` also implicitly declares a defaulted `==`, so all six comparisons work. The operator must be `const`, and it is defined as deleted if a member has no usable `<=>`.
code
cpp · 23 lines#include <compare>
#include <cstdio>
#include <type_traits>
struct Money {
int currency_code; // compared first: declaration order
long long cents;
auto operator<=>(const Money&) const = default; // also declares a defaulted ==
};
struct Rate {
long long base;
double factor; // a double member makes the result partial_ordering
auto operator<=>(const Rate&) const = default;
};
static_assert(std::is_same_v<decltype(Money{} <=> Money{}), std::strong_ordering>);
static_assert(std::is_same_v<decltype(Rate{} <=> Rate{}), std::partial_ordering>);
int main() {
Money usd{840, 500}, eur{978, 100};
std::printf("%d %d %d\n", usd < eur, usd == usd, usd >= eur); // 1 1 0
}go deeper
Know that one defaulted <=> gives a C++20 class the relational operators and an ==, and that it needs the <compare> header.
Explain the lexicographic, declaration-order comparison, how the return category is chosen, and the implicitly declared defaulted ==.
Show when member order or a floating member makes the defaulted ordering wrong for the domain, and when it is deleted because a member cannot be compared.
Decide which value types should be ordered at all, and whether an arbitrary but consistent order is acceptable for map keys versus business logic.
## One operator instead of six Before C++20 an ordered value type needed `<`, `>`, `<=`, `>=`, `==` and `!=`, usually six hand-written functions or a base-class helper. C++20 introduced the **three-way comparison operator** `<=>`. `a <=> b` returns an object that says whether `a` is less than, equivalent to, or greater than `b` (or, for partial orders, unordered), and the compiler derives the relational operators from it: - `a < b` is evaluated as `(a <=> b) < 0`, and similarly for `>`, `<=` and `>=`. - It also tries the **reversed** form, `0 < (b <=> a)`, so mixed-type comparisons work in both orders. ## What = default generates `auto operator<=>(const Money&) const = default;` asks the compiler for the body. The rules from the standard's section on defaulted comparisons are: 1. The function must be a member or friend with two `const Money&` (the implicit object counts) or two `Money` parameters. As a member it must be `const`; clang otherwise reports `defaulted member three-way comparison operator must be const-qualified`. 2. It builds the list of **subobjects**: direct bases in declaration order, then non-static data members in declaration order, with arrays expanded element by element. 3. It compares corresponding subobjects with `<=>` and returns the **first result that is not equal**; if all are equal it returns `equal`. This is a lexicographic comparison, so **member order is part of the ordering**. 4. It is **defined as deleted** if some member has no usable `<=>`. Clang warns `explicitly defaulted three-way comparison operator is implicitly deleted` at the declaration and errors at the first use. ## The return type With `auto`, the return type is the common comparison category of the members' results: | Members | Each member's `<=>` returns | Defaulted result | |---|---|---| | `int`, `long long`, `std::string` | `std::strong_ordering` | `std::strong_ordering` | | any member giving `std::weak_ordering` | weak | `std::weak_ordering` | | any `double` or `float` member | `std::partial_ordering` | `std::partial_ordering` | The categories differ in what they promise. **`strong_ordering`** means equivalent values are interchangeable. **`weak_ordering`** allows equivalent but distinguishable values, such as case-insensitive strings. **`partial_ordering`** allows **unordered** pairs: with a NaN, `a < b`, `a > b` and `a == b` are all false. The code example checks two of these with `static_assert`. ## The == that comes with it If the class does not declare any `operator==`, defaulting `<=>` **implicitly declares a defaulted `operator==`** with the same parameters, returning `bool`. So a single line gives all six operators: four from `<=>` and `==` and `!=` from the implicit `==`. Note that `==` is **not** computed from `<=>`; it is its own memberwise comparison, which can stop early. ## Members that only have < and == If a member's type predates C++20 and offers only `operator<` and `operator==`, the `auto` form fails: the defaulted `<=>` is deleted because that member has no usable `<=>`. Clang warns `explicitly defaulted three-way comparison operator is implicitly deleted`. Naming the return type fixes it: ```cpp struct Entry { Legacy key; // has only operator< and operator== std::strong_ordering operator<=>(const Entry&) const = default; }; ``` With a declared category, the compiler uses a **synthesized three-way comparison** for such members: `a == b ? equal : a < b ? less : greater`. You promise the category, and the compiler builds it from the two old operators. ## Design points for Money - **Member order is the sort order.** In the code example, `currency_code` is declared first, so amounts sort by currency and then by cents. If that is not the order the domain wants, reorder the members or write `<=>` by hand. - **Is the order meaningful at all?** Sorting USD before EUR by a numeric code is an arbitrary but consistent order. That is fine for keys in a `std::map`, but misleading if code reads `usd < eur` as "is worth less". Writing the operator by hand can make cross-currency pairs **unordered** instead. - Include `<compare>` when you name a category type yourself; the defaulted `auto` form still needs the header for the result types.
- If Money also declares its own operator==, what does a defaulted <=> still give?The four relational operators. The implicit defaulted `==` is declared only when the class declares no `operator==` at all; with a user-declared one, that one is used for `==` and `!=`, and the defaulted `<=>` serves `<`, `>`, `<=` and `>=`.
- Why does a double member turn the result into std::partial_ordering?`double <=> double` returns `std::partial_ordering`, because a NaN is neither less than, equal to nor greater than any value. The defaulted operator returns the weakest category among its members, so one `double` makes the whole comparison partial.
- A defaulted <=> compares members in alphabetical or random order
- A defaulted <=> always returns std::strong_ordering
- With a defaulted <=>, the compiler evaluates == as (a <=> b) == 0
- A defaulted <=> may be a non-const member function
- Member order has no effect on how a defaulted <=> sorts
Assumes C++20 or later: operator<=>, the comparison categories in <compare>, defaulted comparisons and the implicit == are C++20 features.