liveBook · Manning

Tuple

As explained in 100 C++ Mistakes and How to Avoid Them

A tuple is a fixed-size aggregate that stores values of potentially different types in a specified order without requiring user-supplied field names.

Mistake 16 is modeling every small aggregate as a named structure. Repeated POD definitions and constructors add clutter and make simple data harder to maintain. A tuple offers a compact alternative when full class semantics are unnecessary. section 3.7

Define a tuple by listing its element types: `using Student = std::tuple<std::string, int, double>;`. Construct it like the structure version, but access values with `std::get<0>`, `std::get<1>`, and `std::get<2>` in specification order. The trade-off is that fields have no user-supplied names; structured binding is identified as a better access method. section 3.7

Student aggregate

A `Student` tuple stores `"Susan"`, `23`, and `3.85` as a string, integer, and double. A template alias can generalize the element types further, but identical tuple definitions for `Student` and `Employee` become the same type, creating a serious design risk. section 3.7

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains definition, construction, indexed access, generalization, and type-identity risks, while pointing to structured binding for improved access.
Examples
Uses a Student aggregate containing a name, age, and GPA, plus a templated tuple alias.
What it assumes
Assumes familiarity with structures and aggregate fields while reducing the need to write constructors and repeated type definitions.
What you can do after
Build it from scratch with std::tuple, initialize heterogeneous values, and retrieve them by index.
How it connects
Connects tuples with structures, PODs, templates, and structured binding.

Also explained in

Compare how 15 books explain tuple →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.