skip to content

How does std::tie give a C++ Version struct a lexicographic operator<, and what does C++20's defaulted operator<=> change?

level: seniorimportance: should knowfreq 45%

answer

  1. a tuple of references
  2. first differing element decides
  3. both member lists must match
  4. declaration order, base classes first
  5. tie also unpacks by assignment

basics

~20 s

std::tie builds tuples of references to the members, and tuple comparison is lexicographic, so tie(a.major, a.minor) < tie(b.major, b.minor) compares in order without copying. C++20 replaces the idiom with a defaulted operator<=> that compares members in declaration order.

solid answer

~40 s

`std::tie(a.major, a.minor, a.patch)` returns a `std::tuple<const int&, const int&, const int&>`, so nothing is copied. Tuple comparison is **lexicographic**: it compares element 0, and only when those are equal moves on to element 1, and so on. Writing `operator<` as `std::tie(...) < std::tie(...)` therefore gives a correct strict weak ordering in one line, usable as a `std::set` key. The idiom has a classic bug: the two `tie` lists must name the same members in the same order, and a slip such as `std::tie(b.major, a.minor)` compiles silently. C++20's `auto operator<=>(const Version&) const = default;` generates the comparison from the class itself, bases first and then members in declaration order, and implicitly declares a defaulted `operator==` too, so the idiom is only needed before C++20.

code

cpp · 31 lines
cpp
#include <compare>
#include <iostream>
#include <set>
#include <tuple>

struct Version {                       // the C++11 idiom
    int major, minor, patch;
    friend bool operator<(const Version& a, const Version& b) {
        return std::tie(a.major, a.minor, a.patch) < std::tie(b.major, b.minor, b.patch);
    }
    friend bool operator==(const Version& a, const Version& b) {
        return std::tie(a.major, a.minor, a.patch) == std::tie(b.major, b.minor, b.patch);
    }
};

struct Version20 {                     // C++20: one defaulted line
    int major, minor, patch;
    auto operator<=>(const Version20&) const = default;   // also declares ==
};

int main() {
    std::cout << std::boolalpha
              << (Version{1, 10, 0} < Version{1, 9, 7}) << ' '     // false
              << (Version{1, 2, 3} == Version{1, 2, 3}) << '\n';   // true
    std::set<Version> releases{{2, 0, 0}, {1, 10, 0}, {1, 9, 7}};
    for (const auto& v : releases)
        std::cout << v.major << '.' << v.minor << '.' << v.patch << ' ';
    std::cout << '\n';                                             // 1.9.7 1.10.0 2.0.0
    std::cout << (Version20{1, 10, 0} > Version20{1, 9, 7}) << ' '
              << (Version20{1, 2, 3} == Version20{1, 2, 3}) << '\n';  // true true
}

go deeper

for a junior

Recall that std::tie makes a tuple of references and that tuples compare element by element.

for a middle

Explain lexicographic tuple comparison, why tie avoids copies, and how std::ignore works when unpacking.

for a senior

Show the mismatched-list and stale-list bugs, the converting-assignment trap in unpacking, and when you move a type to a defaulted operator<=>.

for a principal

Set the team rule: defaulted comparisons where declaration order is the right order, a single key() helper otherwise, and tests that pin the ordering.

## The problem: an ordering over several fields A `Version { int major, minor, patch; }` must sort `1.9.7` before `1.10.0` before `2.0.0`. That is a **lexicographic** comparison: compare `major`; if equal, compare `minor`; if equal, compare `patch`. Written by hand it is a ladder of `if` statements that is easy to get wrong, and a wrong ladder breaks the **strict weak ordering** that `std::set`, `std::map` and `std::sort` require. ## How the std::tie idiom works `std::tie(xs...)` returns `std::tuple<Xs&...>`: a tuple of **lvalue references** to its arguments. Inside a `const` member or a function taking `const Version&`, the references are `const int&`. Two facts make the idiom work: 1. **No copies.** The tuple holds references, so comparing two `Version` objects allocates nothing and copies nothing, even if the members were `std::string`s. 2. **Tuple comparison is lexicographic.** The standard defines `<` for tuples element by element: the first unequal pair decides, and if all are equal neither tuple is less. Since C++20 the tuple's comparisons are specified through `operator<=>` and the relational operators are rewritten from it, but the observable order is unchanged. ```cpp friend bool operator<(const Version& a, const Version& b) { return std::tie(a.major, a.minor, a.patch) < std::tie(b.major, b.minor, b.patch); } ``` Compared with `std::make_tuple`, which would copy each member into a new tuple, `std::tie` is the cheap choice. `std::forward_as_tuple` would also avoid copies, but `std::tie` states the intent. ## The bugs the idiom invites - **Mismatched lists.** `std::tie(a.major, a.minor) < std::tie(b.major, a.minor)` compiles and silently ignores `b.minor`. Nothing checks that the two sides mirror each other. - **Forgotten members.** Adding a `build` field to the struct does not update the `tie` lists, so for two versions differing only in `build` neither is less than the other, while an `==` written separately may say they differ. - **Inconsistent operators.** Writing `<` with `tie` and `==` by hand invites the two to disagree. A common defence is a single private helper used by every operator: 1. Write `auto key() const { return std::tie(major, minor, patch); }` once. 2. Define `operator<` as `a.key() < b.key()` and `operator==` as `a.key() == b.key()`. 3. Add a unit test that sorts a handful of versions such as `1.9.7`, `1.10.0` and `2.0.0`, so a later edit to `key()` that breaks the order fails a build. Because `key()` returns references to members of `*this`, its result must not outlive the object; using it inside one comparison expression is safe. ## What C++20 changes C++20 lets the compiler write the comparison: ```cpp struct Version { int major, minor, patch; auto operator<=>(const Version&) const = default; }; ``` The defaulted `operator<=>` compares the **direct base class subobjects in the order of the base-specifier-list, then the non-static data members in declaration order**, recursively expanding arrays. If the class does not declare any `operator==` itself, the compiler also **implicitly declares a defaulted `operator==`**, and the expressions `a < b`, `a >= b` and `a != b` are rewritten in terms of the two. The comparison and the struct can no longer drift apart, at the cost of tying the ordering to declaration order: reordering members for padding reasons now changes how values sort. | | `std::tie` idiom | defaulted `operator<=>` | |---|---|---| | Standard | C++11 | C++20 | | Order of fields | whatever the `tie` lists say | declaration order, bases first | | Copies | none | none | | Risk | mismatched or stale lists | silent change on member reordering | | Custom order | easy | write `operator<=>` by hand | ## std::tie for unpacking The same tool assigns several existing variables from a tuple: `std::tie(status, std::ignore, body) = fetch();`, with `std::ignore` absorbing an element you do not want. The assignment is **positional and converting**: if `fetch()` returns `std::tuple<int, std::string, double>`, that line assigns the `double` to `body`, and `std::string`'s assignment from `char` accepts it after a floating-to-integral conversion. With Apple clang 21 it compiled without a single warning under `-Wall -Wextra -Wconversion`. Structured bindings (C++17) are the safer choice for new variables; `std::tie` remains for assigning variables that already exist.

  • Why is std::make_tuple a worse choice than std::tie inside operator<?
    `std::make_tuple` decays its arguments and stores copies, so every comparison copies each member into two temporary tuples. For `int` members the optimizer usually removes that, but for `std::string` members it means allocations inside a comparator that a sort calls millions of times. `std::tie` stores references and copies nothing.
  • When would you still write operator<=> by hand in C++20?
    When the ordering is not member-wise in declaration order: comparing case-insensitively, ignoring a cache field, comparing a pointer's target instead of its address, or ordering on a different member sequence than the layout. You can still use `std::tie(...) <=> std::tie(...)` inside the hand-written operator, since `std::tuple` provides `operator<=>` in C++20.
  • Is a defaulted operator<=> on a struct with a double member a strong ordering?
    No. `double`'s `<=>` yields `std::partial_ordering` because NaN is unordered, so a defaulted `auto operator<=>` on such a struct also returns `std::partial_ordering`. A `std::set` keyed on it then misbehaves if a NaN ever gets in, exactly as it would with a raw `double` key.

Sorting a class list by surname, then first name, then birth date: the first column that differs decides, and the later columns are only consulted on a tie.

  • std::tie copies the members into a tuple before comparing them
  • tuple operator< compares every element and combines the results
  • a mismatched member in one tie list causes a compile error
  • a defaulted operator<=> compares members in alphabetical order
  • you must still declare operator== separately after defaulting operator<=>
  • std::tie unpacking refuses to compile when element types differ

Assumes C++20 for the defaulted operator<=> and its implicit operator==; the std::tie idiom itself works from C++11.