Module 3 · Strings and containers
3.4optional, variant and tuple
Hold a value that may be missing with std::optional, one of several types with std::variant, and several values at once with std::pair and std::tuple, then unpack them with structured bindings.
On this page
- Key terms
- In 30 seconds
- std::optional: a value or nothing
- Returning a value that might not exist
- std::variant: one of several types
- Asking and reading at once: std::get_if
- Handling every case with std::visit
- std::pair and std::tuple: several values at once
- Structured bindings
- A copy, or the original
- Every part needs a name
- Which one should I use?
- Under the hood
- Common pitfalls
- Reading an empty optional with *
- if (opt) asks “is there a value?”, not “is it nonzero?”
- Try it yourself
Key terms
std::optional<T>- Holds either one
Tor nothing. A new optional is empty, and assigningstd::nulloptempties it again. From<optional>. *opt,value()andvalue_or(x)- Ways to get an optional's value.
*optdoesn't check (undefined behavior when empty),value()throwsstd::bad_optional_accesswhen empty, andvalue_or(x)returnsxinstead. std::variant<A, B, …>- Holds exactly one value at a time, of one of the listed types, called its alternatives. From
<variant>. std::getandstd::get_ifstd::get<T>(v)returns theTin a variant and throwsstd::bad_variant_accessif it holds something else.std::get_if<T>(&v)returns a pointer to it, ornullptr.std::visit(f, v)- Calls
f, the visitor, with whatever the variantvholds. The visitor must accept every alternative. std::pair<A, B>- Two values stored together,
firstandsecond. From<utility>. std::tuple<A, B, C, …>- Any fixed number of values, of any types, reached by position with
std::get<0>,std::get<1>and so on. From<tuple>. - structured binding
auto [a, b] = x;gives a name to each part of a pair, tuple, array or struct.auto&makes the names refer to the parts ofxitself.
Some values don’t fit one plain type. A read’s quality score might be missing. A cell in a spreadsheet might hold a number or some text. A function might need to return a minimum and a maximum together. The standard library has a small type for each case: std::optional for a value that may be missing, std::variant for one of several types, and std::pair and std::tuple for several values at once.
In 30 seconds
std::optional<T>holds aTor nothing (std::nullopt). Check it withif (opt)before you read*opt, or usevalue_or(fallback).std::variant<A, B>holds anAor aB, and knows which.std::visitruns the right code for whichever it holds.std::pairholds two values andstd::tupleany number, reached with.first/.secondorstd::get<0>.- A structured binding,
auto [a, b] = x;, names the parts. Add&to change the original.
std::optional: a value or nothing
std::optional<T> (from <optional>) holds either one T or nothing. A new optional is empty. Assigning a value fills it, and assigning std::nullopt empties it again:
#include <optional>
#include <print>
std::optional<double> quality; // empty
std::println("{}", quality.has_value());
quality = 37.5;
if (quality) {
std::println("quality {}", *quality);
}
std::println("{}", quality.value()); // checks, then returns the value
quality = std::nullopt;
std::println("{}", quality.value_or(0.0));Output
false quality 37.5 37.5 0
has_value(), or the optional itself as a condition, says whether there’s a value. *quality reads the value without checking, so use it only after a check. value() checks, and throws a std::bad_optional_access exception if there’s no value. value_or(0.0) returns the value, or 0.0 if there isn’t one.
Returning a value that might not exist
An optional is a natural return type for a search that might find nothing. Here’s a function that finds the first unknown base, N, in a read:
#include <cstddef>
#include <optional>
#include <print>
#include <string>
std::optional<std::size_t> first_unknown(const std::string& read) {
for (std::size_t i = 0; i < read.size(); ++i) {
if (read[i] == 'N') {
return i;
}
}
return std::nullopt;
}
int main() {
if (auto pos = first_unknown("GATNACA")) {
std::println("N at {}", *pos);
}
std::println("{}", first_unknown("GATTACA").has_value());
}Output
N at 3 false
if (auto pos = …) declares pos and tests it in one step, and pos exists only inside the if. return i; turns the std::size_t into a filled optional. The return type tells the caller that the answer may be missing, and since an optional isn’t a number, the caller has to unwrap it to get one: that’s the moment to check. Compare std::string::find, which returns a special number, std::string::npos, that’s easy to use by mistake. Using std::optional and std::expected to report errors is the subject of optional and expected for errors.
std::variant: one of several types
std::variant<A, B, …> (from <variant>) holds exactly one value at a time, of one of the listed types, called its alternatives. It also remembers which one it holds. Think of a cell read from a spreadsheet, which might be a whole number, a decimal or text:
#include <print>
#include <string>
#include <variant>
std::variant<int, double, std::string> cell = 42;
std::println("{} {}", cell.index(), std::get<int>(cell));
cell = 3.5;
std::println("{} {}", cell.index(), std::get<double>(cell));
cell = std::string("N/A");
std::println("{}", std::holds_alternative<std::string>(cell));Output
0 42 1 3.5 true
index() gives the position of the alternative it holds now, from 0. std::holds_alternative<T>(cell) asks whether it holds a T. std::get<T>(cell) returns the value, if it really is a T. If it isn’t, std::get throws a std::bad_variant_access exception, and with nothing to catch it the program stops:
#include <print>
#include <variant>
std::variant<int, double> cell = 3; // holds an int
std::println("{}", std::get<double>(cell)); // throws bad_variant_accessThis fails when it runs
terminate called after throwing an instance of 'std::bad_variant_access' what(): std::get: wrong index for variant
Asking and reading at once: std::get_if
std::get_if<T> takes the variant’s address and returns a pointer to the value if it holds a T, or nullptr if it doesn’t. So one if checks and reads:
#include <print>
#include <string>
#include <variant>
std::variant<int, double, std::string> cell = 3.5;
if (const double* d = std::get_if<double>(&cell)) {
std::println("a decimal: {}", *d);
}
if (std::get_if<int>(&cell) == nullptr) {
std::println("not a whole number");
}Output
a decimal: 3.5 not a whole number
Handling every case with std::visit
Checking each alternative with if gets long, and it’s easy to miss one. std::visit(visitor, v) calls the visitor with whatever v holds. A visitor is often a small struct with one operator() per alternative. operator() is a function that belongs to the struct and runs when you call an object of that type like a function; Operators and comparisons covers it. Read each line of Describe as “what to do with an int”, and so on:
#include <print>
#include <string>
#include <variant>
#include <vector>
struct Describe {
void operator()(int n) { std::println("whole number {}", n); }
void operator()(double d) { std::println("decimal {}", d); }
void operator()(const std::string& s) { std::println("text {}", s); }
};
int main() {
std::vector<std::variant<int, double, std::string>> row = {
7, 2.5, std::string("N/A")};
for (const auto& cell : row) {
std::visit(Describe{}, cell);
}
}Output
whole number 7 decimal 2.5 text N/A
Describe{} creates a Describe object to pass in. If the visitor has no case for one of the alternatives, the program doesn’t compile. GCC’s message is about std::invoke_result having “no type named type”: there’s nothing to call with a std::string:
#include <print>
#include <string>
#include <variant>
struct Describe {
void operator()(int n) { std::println("whole number {}", n); }
void operator()(double d) { std::println("decimal {}", d); }
};
int main() {
std::variant<int, double, std::string> cell = std::string("N/A");
std::visit(Describe{}, cell);
}The compiler rejects this
In file included from main.cpp:3:
/usr/include/c++/15/variant: In instantiation of ‘constexpr bool std::__detail::__variant::__check_visitor_results(std::index_sequence<_Idx ...>) [with _Visitor = Describe; _Variant = std::variant<int, double, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >&; long unsigned int ..._Idxs = {0, 1, 2}; std::index_sequence<_Idx ...> = std::integer_sequence<long unsigned int, 0, 1, 2>]’:
/usr/include/c++/15/variant:1944:44: required from ‘constexpr std::__detail::__variant::__visit_result_t<_Visitor, _Variants ...> std::visit(_Visitor&&, _Variants&& ...) [with _Visitor = Describe; _Variants = {variant<int, double, __cxx11::basic_string<char, char_traits<char>, allocator<char> > >&}; __detail::__variant::__visit_result_t<_Visitor, _Variants ...> = void]’
| constexpr bool __visit_rettypes_match = __detail::__variant::
| ~~~~~~~~~~~~~~~~~~~~~
| __check_visitor_results<_Visitor, _Vp>(
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
| make_index_sequence<variant_size_v<remove_reference_t<_Vp>>>());
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:12:15: required from here
12 | std::visit(Describe{}, cell);
| ~~~~~~~~~~^~~~~~~~~~~~~~~~~~
/usr/include/c++/15/variant:1129:14: error: no type named ‘type’ in ‘struct std::invoke_result<Describe, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&>’
| return __same_types<
| ^~~~~~~~~~~~~
| invoke_result_t<_Visitor, __get_t<_Idxs, _Variant>>...
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| >;
| ~
compilation terminated due to -fmax-errors=1.The check only sees whether some case accepts each alternative. Without the double case, a double would quietly go to the int case, converted, and the program would compile.
When every alternative is handled the same way, a lambda is shorter: a small unnamed function written in place, covered in Lambdas. Its auto parameter accepts a value of any type, so it handles every alternative:
#include <print>
#include <string>
#include <variant>
std::variant<int, double, std::string> cell = 2.5;
std::visit([](const auto& value) { std::println("{}", value); }, cell);Output
2.5
std::pair and std::tuple: several values at once
std::pair<A, B> (from <utility>) holds two values, named first and second. std::tuple<A, B, C, …> (from <tuple>) holds any fixed number, which you reach by position with std::get<0>, std::get<1> and so on. The position goes in angle brackets because the compiler needs to know it when it compiles: it must be a constant, not a value worked out while the program runs.
#include <print>
#include <string>
#include <tuple>
#include <utility>
std::pair<std::string, int> best = {"sample_b", 120};
std::println("{} {}", best.first, best.second);
std::tuple<std::string, int, double> read = {"r1", 150, 0.98};
std::println("{} {}", std::get<0>(read), std::get<2>(read));
std::get<1>(read) = 151;
std::println("{}", read);Output
sample_b 120
r1 0.98
("r1", 151, 0.98)std::println prints a pair or tuple in parentheses. A common use is returning more than one value from a function:
#include <print>
#include <tuple>
#include <vector>
std::tuple<int, int, double> summary(const std::vector<int>& scores) {
int lowest = scores[0];
int highest = scores[0];
int total = 0;
for (int s : scores) {
lowest = s < lowest ? s : lowest;
highest = s > highest ? s : highest;
total += s;
}
double mean =
static_cast<double>(total) / static_cast<double>(scores.size());
return {lowest, highest, mean};
}
int main() {
auto [lowest, highest, mean] = summary({30, 12, 45, 9});
std::println("{} {} {}", lowest, highest, mean);
}Output
9 45 24
The caller has to know that position 0 is the lowest and position 2 is the mean; the tuple’s type only says int, int, double. Once the values travel further than one call, a struct with named fields says more. Structs and classes covers structs.
Structured bindings
The last example unpacked a tuple with auto [lowest, highest, mean] = …. That’s a structured binding: one name for each part, in order. It works on a std::pair, a std::tuple, a std::array, a C array, and a struct whose fields are all public, like the plain structs from Stack, heap and lifetime:
#include <array>
#include <print>
#include <string>
struct Read {
std::string id;
int length;
};
int main() {
std::array<int, 3> pixel = {255, 128, 0};
auto [r, g, b] = pixel;
std::println("{} {} {}", r, g, b);
Read read = {"r1", 150};
auto [id, length] = read;
std::println("{} {}", id, length);
}Output
255 128 0 r1 150
A copy, or the original
auto [a, b] = x; copies x, and the names refer to the parts of the copy. Changing them leaves x alone. auto& [a, b] = x; copies nothing: the names refer to the parts of x itself. const auto& [a, b] reads without copying, which is what you want for a loop over a map in Maps and sets.
#include <print>
#include <string>
#include <utility>
std::pair<std::string, int> best = {"sample_b", 120};
auto [name, count] = best; // a copy of best
count = 0;
std::println("{}", best.second);
auto& [same_name, same_count] = best; // refers to best
same_count = 0;
std::println("{}", best.second);Output
120 0
Every part needs a name
You have to name every part, even the ones you don’t need, and no more. With too few names, it doesn’t compile:
#include <string>
#include <tuple>
std::tuple<std::string, int, double> read = {"r1", 150, 0.98};
auto [id, length] = read;The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:5:6: error: only 2 names provided for structured binding
5 | auto [id, length] = read;
| ^~~~~~~~~~~~
main.cpp:5:6: note: while ‘std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, double>’ decomposes into 3 elementsThe fix is auto [id, length, quality] = read;. If you only want one part, std::get<1>(read) may be clearer.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
std::optional<T> | A value that may be missing: an optional field, a search that may find nothing. | “Nothing” is its own state, not a special value like -1 that could be mistaken for data. | std::optional<double> quality; |
std::variant<A, B> | A value that is one of a few known types. | It knows which type it holds, and std::visit won’t compile when an alternative has no case that accepts it. | std::variant<int, std::string> cell; |
std::pair<A, B> | Two values that belong together for a moment: a key and a value, a lowest and a highest. | No new type to write, and maps already use it. | std::pair<int, int> range = {7, 45}; |
std::tuple<A, B, C> | Three or more values returned together, unpacked right away. | No new type to write. | auto [lo, hi, mean] = summary(v); |
| A struct | The values are kept, passed around or stored. | Each field has a name, so the code says what it holds. | struct Read { std::string id; int length; }; |
Rule of thumb: use std::optional for “maybe”, std::variant for “one of”, and a struct for “all of these”. Keep std::pair and std::tuple for values that are unpacked right where they’re made.
Under the hood
None of these types allocates heap memory of its own. A std::optional<T> is the T plus a bool that says whether it’s there. A std::variant has room for its largest alternative, plus a small number for the index. A std::pair is its two values side by side. These are the sizes on this platform (64-bit Linux, GCC’s standard library):
#include <optional>
#include <print>
#include <utility>
#include <variant>
std::println("optional<int>: {}", sizeof(std::optional<int>));
std::println("optional<double>: {}", sizeof(std::optional<double>));
std::println("variant<int, double>: {}", sizeof(std::variant<int, double>));
std::println("pair<int, double>: {}", sizeof(std::pair<int, double>));Output
optional<int>: 8 optional<double>: 16 variant<int, double>: 16 pair<int, double>: 16
| Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Size |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
std::optional<int> | int4 bytes | has value1 byte · tag | padding3 bytes | 8 bytes | |||||||||||||
std::variant<int, double> holding int | int4 bytes | unused4 bytes | index 01 byte · tag | padding7 bytes | 16 bytes | ||||||||||||
std::variant<int, double> holding double | double8 bytes | index 11 byte · tag | padding7 bytes | 16 bytes | |||||||||||||
std::pair<int, double> | first: int4 bytes | padding4 bytes | second: double8 bytes | 16 bytes | |||||||||||||
On 64-bit Linux with GCC's standard library: std::optional<int> is 8 bytes, a 4-byte int, a 1-byte has-value flag and 3 bytes of padding. std::variant<int, double> is 16 bytes: 8 bytes of storage, big enough for a double, then a 1-byte index and 7 bytes of padding. Holding an int, it uses 4 of the 8 storage bytes. std::pair<int, double> is 16 bytes: the int, 4 bytes of padding, then the double.
The padding bytes are unused space the compiler adds so that each value starts at an address its type can be read from quickly: a double at a multiple of 8. Module 9 explains alignment and padding. Padding is why an optional<double> takes 16 bytes rather than 9.
A structured binding doesn’t make separate variables either. auto [a, b] = x; makes one hidden copy of x, and a and b are names for its parts. With auto&, the hidden variable is a reference to x.
PerformanceCheap to return
Because they don’t allocate on their own, returning an optional, a variant or a tuple from a function costs about the same as returning its values one by one.
Common pitfalls
Reading an empty optional with *
* doesn’t check whether there’s a value. On an empty optional, it’s undefined behavior. GCC’s standard library checks this in builds without optimization, like this one, so here the program stops with a failed assertion. An optimized build won’t check, and might print garbage and carry on (Undefined behavior has more):
#include <optional>
#include <print>
std::optional<int> best_score; // never filled in
std::println("{}", *best_score);This fails when it runs
/usr/include/c++/15/optional:1186: constexpr _Tp& std::optional<_Tp>::operator*() & [with _Tp = int]: Assertion 'this->_M_is_engaged()' failed.
Check with if (best_score) first, or use best_score.value_or(0) if there’s a sensible default.
if (opt) asks “is there a value?”, not “is it nonzero?”
An optional that holds 0 or false still holds a value, so it counts as true in a condition:
#include <optional>
#include <print>
std::optional<int> missing_reads = 0;
if (missing_reads) {
std::println("has a value: {}", *missing_reads);
}
if (missing_reads && *missing_reads > 0) {
std::println("some reads are missing");
}Output
has a value: 0
To test the value, unwrap it: *missing_reads > 0 after the check, or missing_reads.value_or(0) > 0.
Try it yourself
Try it yourself
min_max returns {0, 0} for an empty vector, which looks like real scores. Change it to return a std::optional<std::pair<int, int>> that’s empty when there are no scores, and make report print no scores in that case.
#include <print>
#include <utility>
#include <vector>
std::pair<int, int> min_max(const std::vector<int>& values) {
if (values.empty()) {
return {0, 0}; // looks like real scores
}
int lo = values[0];
int hi = values[0];
for (int v : values) {
lo = v < lo ? v : lo;
hi = v > hi ? v : hi;
}
return {lo, hi};
}
void report(const std::vector<int>& scores) {
auto [lo, hi] = min_max(scores);
std::println("lowest {}, highest {}", lo, hi);
}
int main() {
report({30, 12, 45, 7});
report({});
}Expected output
lowest 7, highest 45 no scores
Show a hint
Change the return type to std::optional<std::pair<int, int>> and return std::nullopt for an empty vector. In report, write if (auto range = min_max(scores)), then auto [lo, hi] = *range; inside.
Show a solution
#include <optional>
#include <print>
#include <utility>
#include <vector>
std::optional<std::pair<int, int>> min_max(const std::vector<int>& values) {
if (values.empty()) {
return std::nullopt;
}
int lo = values[0];
int hi = values[0];
for (int v : values) {
lo = v < lo ? v : lo;
hi = v > hi ? v : hi;
}
return std::pair<int, int>{lo, hi};
}
void report(const std::vector<int>& scores) {
if (auto range = min_max(scores)) {
auto [lo, hi] = *range;
std::println("lowest {}, highest {}", lo, hi);
} else {
std::println("no scores");
}
}
int main() {
report({30, 12, 45, 7});
report({});
}std::optional<std::pair<int, int>> says in the type that there may be no answer. return std::pair<int, int>{lo, hi}; makes the pair, and it converts to a filled optional. (A bare return {lo, hi}; no longer compiles: the braces would have to build the optional itself, which can't be made from two ints.) In report, if (auto range = …) checks for a value, *range is the pair, and the structured binding names its two parts. The empty case now prints no scores instead of a made-up 0 and 0.
Saved in this browser only.