When should a C++ function return a named struct instead of a std::tuple such as std::tuple<int, std::string, double>?
answer
- names are documentation
- get<2> means what?
- bindings work on structs too
- tuples suit generic code
- layout and triviality differ
basics
~20 sReturn a named struct whenever callers will read the fields by meaning: status, payload and latencyMs say what get<0>, get<1> and get<2> do not. Structs still unpack with structured bindings; keep tuples for generic code that builds or forwards values by position.
solid answer
~40 sA tuple names types, not meanings: `std::get<2>(result)` hides that element 2 is a latency in milliseconds, and two elements of the same type can be swapped without a compile error. A struct like `FetchResult { int status; std::string payload; double latencyMs; }` documents itself, unpacks with the same `auto [status, payload, latencyMs] = fetch();` since C++17, accepts C++20 designated initializers, and gets comparisons from a defaulted `operator<=>`. It is also an aggregate and, with trivial members, trivially copyable, while the standard declares `std::tuple`'s copy assignment explicitly and leaves its member layout unspecified. Tuples remain right where positions are the point: variadic code, `std::apply`, `std::tuple_cat`, ad hoc keys, and one-off local helpers.
code
cpp · 29 lines#include <iostream>
#include <string>
#include <tuple>
#include <type_traits>
// Positional: the reader must remember that element 2 is the latency in ms.
std::tuple<int, std::string, double> fetchTuple() { return {200, "body", 12.5}; }
// Named: the declaration is the documentation.
struct FetchResult {
int status;
std::string payload;
double latencyMs;
};
FetchResult fetch() { return {.status = 200, .payload = "body", .latencyMs = 12.5}; }
int main() {
auto t = fetchTuple();
std::cout << std::get<0>(t) << ' ' << std::get<2>(t) << '\n';
auto [status, payload, latencyMs] = fetch(); // a struct unpacks just as well
std::cout << status << ' ' << payload << ' ' << latencyMs << '\n';
std::cout << fetch().latencyMs << '\n';
struct Pt { int x, y; };
std::cout << std::boolalpha
<< std::is_trivially_copyable_v<Pt> << ' ' // true
<< std::is_trivially_copyable_v<std::tuple<int, int>> << '\n'; // false in libc++
}go deeper
Recall that structs name their fields and tuples only number them, and that both unpack with structured bindings.
Explain how positional access and same-typed elements cause bugs, and where tuples fit: apply, tuple_cat and generic code.
Show the layout and triviality differences that matter at binary boundaries, and how a struct makes interface changes fail loudly.
Set the interface rule for the code base: named result types for public functions, tuples only in generic plumbing, and how to migrate existing pair-returning APIs.
## The question behind the question When an interviewer asks "tuple or struct?", they are checking whether you know what each one **costs the reader** and what each one **does for generic code**. The language is neutral; the trade-offs are concrete. ## What a tuple gives up Take a function that returns a status code, a payload and a latency: ```cpp std::tuple<int, std::string, double> fetch(); ``` - **Positions carry no meaning.** At every call site, `std::get<0>`, `std::get<1>` and `std::get<2>` must be decoded from documentation. A reader cannot tell a latency in milliseconds from one in seconds. - **Same-typed elements swap silently.** A `std::tuple<double, double>` of `(latency, timeout)` accepts its arguments in either order, and `std::get<double>` cannot be used at all because the type is not unique. - **Evolution is awkward.** Inserting an element shifts every later index, and every `std::get<N>` on the shifted elements now reads the wrong field, often still compiling if the types happen to match. - **Layout and triviality are not yours.** The standard does not specify the order of a tuple's elements in memory. libc++ stores them in declaration order (offsets 0, 4 and 8 for `std::tuple<char, int, char>` with Apple clang 21), while libstdc++ derives each level from the rest of the tuple before the head element, which places elements in roughly reverse order. The standard also declares `tuple`'s copy assignment operator instead of defaulting it, and libc++ reports `std::is_trivially_copyable_v<std::tuple<int, int>>` as `false`, so a tuple is a poor fit for `memcpy`, binary I/O or a stable binary interface. ## What a named struct gives you ```cpp struct FetchResult { int status; std::string payload; double latencyMs; }; ``` - **Self-documenting fields.** `result.latencyMs` needs no comment. - **Unpacking is not lost.** Structured bindings (C++17) unpack an aggregate through its data members, so `auto [status, payload, latencyMs] = fetch();` reads the same as with a tuple. - **Construction by name.** C++20 **designated initializers**, `{.status = 200, .payload = "body", .latencyMs = 12.5}`, name the field each value goes to, so a latency cannot land in the status slot by position. The designators must follow declaration order. - **Comparisons for free.** C++20's `auto operator<=>(const FetchResult&) const = default;` gives ordering and equality. - **Loud evolution.** Adding a member makes every `auto [a, b, c] = fetch();` stop compiling, because the number of names must match the number of members. That is a feature: each call site is revisited instead of silently misreading a field. - **A home for behaviour and invariants**, should the type grow them. ## Where a tuple is the right tool | Situation | Prefer | Why | |---|---|---| | Public or long-lived API return value | struct | meaning lives in the names | | Value that crosses a binary interface or is copied with `memcpy` | struct | defined layout, can be trivially copyable | | Generic code returning or forwarding a pack of values | tuple | the element list is a template parameter | | Calling a function with stored arguments | tuple | `std::apply` consumes it | | Joining value lists at compile time | tuple | `std::tuple_cat` | | Composite `std::map` key in a few lines | tuple | `operator<` is lexicographic and built in | | Two-value result of a local lambda | pair or tuple | the scope is tiny | Two cautions on the last rows. A tuple key works in `std::map` because `std::tuple` provides comparison operators, but **the standard provides no `std::hash` for `std::tuple` or `std::pair`**, so `std::unordered_map<std::tuple<int, int>, V>` needs a user-supplied hash. And `std::pair` remains idiomatic in places the library chose it, such as map elements and `std::minmax`, where `first` and `second` are understood by every reader. ## A working rule 1. If more than one call site will read the fields, name them with a struct. 2. If the values are produced or consumed generically, by position, use a tuple. 3. If the result has two fields whose meaning is obvious from context, `std::pair` is acceptable. 4. Never use a tuple to avoid writing a five-line struct in a header that others will read.
- Can std::unordered_map use std::tuple<int, int> as a key without extra code?No. `std::unordered_map` needs `std::hash<Key>`, and the standard specializes `std::hash` for `std::optional` and `std::variant` but not for `std::tuple` or `std::pair`. With libc++ the declaration fails on the implicitly deleted default constructor of `std::hash<std::tuple<int, int>>`. Supply a hash functor that combines the element hashes, or use `std::map`, which only needs the tuple's `operator<`.
- Why might a library keep returning std::pair even when a struct would read better?Because callers already depend on it: `first` and `second`, `std::get` and structured bindings all work on the pair, and changing the return type breaks source and binary compatibility. The standard library likewise still uses `std::pair` for map elements and `insert` results. New interfaces have no such excuse and usually deserve a named type.
A tuple is a spreadsheet row with no header row: the data is all there, but every reader has to remember what column three means.
- you lose structured bindings if you return a struct instead of a tuple
- a tuple is laid out in memory exactly like the equivalent struct
- std::hash works for std::tuple keys out of the box
- adding a member to a struct silently shifts existing bindings
- tuples are faster than structs because access is resolved at compile time
Assumes C++17 structured bindings; designated initializers and defaulted operator<=> for the struct are C++20.