Why does a C++20 class with a hand-written operator<=> reject a == b, and how should the equality operator be added?
answer
- only = default brings ==
- == is never rewritten from <=>
- equality can stop early
- keep the two consistent
basics
~20 sOnly a defaulted operator<=> implicitly declares an ==, and C++20 never rewrites == in terms of <=>. A hand-written <=> therefore leaves a == b with no candidate; declare bool operator==(const Money&) const = default or write it, consistent with <=>.
solid answer
~40 sC++20 rewrites the four relational operators through `<=>` and `!=` through `==`, but **never `==` through `<=>`**. The implicit `operator==` is declared only alongside a **defaulted** `<=>`, and only when the class declares no `operator==`. So when `Money` writes `<=>` by hand, for example to return `std::partial_ordering::unordered` for amounts in different currencies, `a < b` works and `a == b` fails with `invalid operands to binary expression`. Add `bool operator==(const Money&) const = default;` (memberwise) or a hand-written `==`, and keep it **consistent** with `<=>`: `a == b` should be true exactly when `(a <=> b) == 0`. The design reason for keeping them separate is performance: equality can often be decided early, such as two containers of different sizes, while `<=>` must find the first difference.
code
cpp · 21 lines#include <compare>
#include <cstdio>
enum class Currency { USD, EUR };
struct Money {
Currency currency;
long long cents;
std::partial_ordering operator<=>(const Money& rhs) const {
if (currency != rhs.currency) return std::partial_ordering::unordered;
return cents <=> rhs.cents;
}
bool operator==(const Money&) const = default; // not implied by a user-written <=>
};
int main() {
Money usd{Currency::USD, 500}, eur{Currency::EUR, 500};
std::printf("usd < eur: %d, usd > eur: %d\n", usd < eur, usd > eur); // 0, 0
std::printf("usd == eur: %d, usd != eur: %d\n", usd == eur, usd != eur); // 0, 1
}go deeper
Remember that a hand-written <=> does not give you ==; you add it, often with = default.
Explain which operators C++20 rewrites from which, and why only a defaulted <=> declares an implicit ==.
Show why == stays separate for performance, how partial_ordering affects sorting and map keys, and how to keep == consistent with <=>.
Decide whether a domain type should be ordered at all, and where cross-category comparisons are rejected, unordered or handled by explicit comparators.
## The scenario A billing service orders amounts within one currency, but comparing USD with EUR without an exchange rate has no meaning. A hand-written three-way comparison can say so: ```cpp std::partial_ordering operator<=>(const Money& rhs) const { if (currency != rhs.currency) return std::partial_ordering::unordered; return cents <=> rhs.cents; } ``` `usd < eur` and `usd > eur` are now both `false`. But `usd == eur` does not compile: clang reports `invalid operands to binary expression ('Money' and 'Money')`, and so does `usd != eur`. ## Why == is missing Two C++20 rules combine: 1. **The implicit `==` is tied to `= default`.** The standard implicitly declares an `operator==` only for a three-way comparison operator **defined as defaulted**, and only if the class declares no member or friend named `operator==`. A user-written `<=>` declares nothing extra. 2. **`==` is never rewritten from `<=>`.** The rewritten candidates are: `!=` from `==`; `<`, `>`, `<=`, `>=` from `<=>`; and the reversed forms. There is no route from `a == b` to `(a <=> b) == 0`. So with only a hand-written `<=>`, `==` and `!=` have no candidates at all. ## Why the language was designed this way The split was deliberate. Equality is frequently **cheaper** than ordering: - Two `std::vector` or `std::string` objects of different sizes are unequal without looking at a single element, while `<=>` must find the first differing element. - A type may have a meaningful equality and no meaningful order, or an equality that is cheaper to compute than its order. Deriving `==` from `<=>` silently would have made every equality check pay for an ordering. ## How to add it Pick the form that matches what equality means for the type: - **`bool operator==(const Money&) const = default;`** compares `currency` and then `cents`. Here that is exactly right: two amounts are equal only if both match. - A **hand-written `==`** when some members do not take part in the value (a cached display string, a timestamp). Then check **consistency**. `a == b` should be true exactly when `(a <=> b) == 0`, otherwise sorting and lookup will disagree with equality. In the `Money` example both are false for different currencies and agree for the same currency, which the code example demonstrates. ## The interaction table | Class declares | `<`, `>`, `<=`, `>=` | `==` | `!=` | |---|---|---|---| | `<=>` defaulted, no `==` | from `<=>` | implicit defaulted `==` | rewritten from `==` | | `<=>` defaulted, own `==` | from `<=>` | the user's `==` | rewritten from `==` | | `<=>` hand-written, no `==` | from `<=>` | does not compile | does not compile | | `<=>` hand-written, `==` added | from `<=>` | the added `==` | rewritten from `==` | ## Alternatives to an unordered result Returning `unordered` is one answer to the mixed-currency case. The others have different costs: - **Throw** from `operator<=>`. Comparisons are expected not to throw, and a throwing comparator inside `std::sort` or a container leaves the operation half done. - **Assert** a precondition that both amounts share a currency. It makes misuse loud in debug builds, but release builds silently compare cents. - **Offer no ordering** on `Money` at all and give callers named functions or explicit comparators for the cases that make sense. All are defensible. What is not defensible is a defaulted `<=>` that quietly orders by currency code and lets code read the result as "worth less". ## What partial_ordering adds Returning `std::partial_ordering` has consequences beyond `==`: - Standard algorithms and ordered containers such as `std::sort` and `std::map` require a **strict weak ordering**. Mixed-currency elements are not ordered, so a container mixing currencies must use a different comparator, for example one that compares the currency code first. Keep that comparator separate from `operator<`. - `std::partial_ordering::unordered` compared with `0` gives `false` for every relational operator, which is why both `usd < eur` and `usd > eur` print `0` in the code example. The point interviewers listen for is the sentence "only `= default` brings an `==` along, and `==` is never computed from `<=>`".
- Can Money with this partial_ordering be a std::map key with the default comparator?Only if every key has the same currency. `std::less<Money>` uses `<`, and `std::map` needs a strict weak ordering over all keys; mixed currencies are unordered, which breaks that requirement. Pass a comparator that orders by currency first, or key the map by currency.
- If you default == but keep the hand-written <=>, what must you check?That the two agree: `a == b` exactly when `(a <=> b) == 0`. A defaulted `==` compares every member, so if `<=>` ignores a member, such as a cached string, equality and ordering disagree and code mixing sort and find breaks.
- C++20 evaluates a == b as (a <=> b) == 0 when only <=> exists
- Any operator<=> implicitly declares an operator== as well
- Declaring operator!= by hand fixes the missing equality
- An unordered result makes a < b true for one of the two orders
- == and <=> may disagree without consequences
Assumes C++20 or later: three-way comparison, rewritten candidates and the implicit == for a defaulted <=> were all introduced in C++20.