In C++17, how do you find out which alternative a std::variant holds and read it without risking an exception?
answer
- a zero-based number
- a yes-or-no type test
- a pointer that may be null
- the throwing reader
basics
~10 sAsk index() for the zero-based alternative or holds_alternative<T>(v) for a type test, then read with std::get_if<T>(&v), which returns nullptr on a mismatch. std::get<T>(v) throws std::bad_variant_access when v holds another alternative.
solid answer
~40 sA `std::variant<Ping, Data, Close>` (C++17, `<variant>`) always holds exactly one alternative, ignoring the rare valueless state. `v.index()` returns its zero-based position, and `std::holds_alternative<Data>(v)` tests for one type. To read, `std::get_if<Data>(&v)` takes a **pointer** to the variant and returns a pointer to the `Data` inside, or `nullptr` if something else is active, so `if (const Data* d = std::get_if<Data>(&v))` tests and reads in one step without exceptions. `std::get<Data>(v)` or `std::get<1>(v)` returns a reference but throws `std::bad_variant_access` on a mismatch. Getting by type requires the type to occur exactly once in the list; `variant<int, int>` must use indexes. A default-constructed variant holds a value-initialized first alternative, which is why `std::monostate` is often listed first.
code
cpp · 32 lines#include <cstdint>
#include <iostream>
#include <string>
#include <variant>
struct Ping { std::uint64_t seq; };
struct Data { std::string payload; };
struct Close { int code; };
using Message = std::variant<Ping, Data, Close>;
void handle(const Message& m) {
std::cout << "index " << m.index() << ": ";
if (const Data* d = std::get_if<Data>(&m)) { // nullptr unless m holds Data
std::cout << "data " << d->payload << '\n';
} else if (std::holds_alternative<Ping>(m)) {
std::cout << "ping " << std::get<Ping>(m).seq << '\n';
} else {
std::cout << "close " << std::get<2>(m).code << '\n';
}
}
int main() {
handle(Ping{7});
handle(Data{"hello"});
handle(Close{1000});
Message m = Close{1001};
try {
std::cout << std::get<Data>(m).payload << '\n';
} catch (const std::bad_variant_access&) {
std::cout << "std::get<Data> threw std::bad_variant_access\n";
}
}go deeper
Recall the reading tools: index(), holds_alternative<T>, get_if<T>(&v) returning a pointer or nullptr, and get<T> throwing std::bad_variant_access on a mismatch.
Explain default construction of the first alternative, std::monostate as an explicit empty state, and why getting by type needs the type to appear exactly once.
Prefer visitation or get_if over index literals that break when alternatives are reordered, and keep bad_variant_access for broken assumptions rather than control flow.
Set conventions for sum types in a codebase: distinct wrapper structs instead of repeated types, monostate only where an empty state is real, and visitation as the default reading style.
## What std::variant is `std::variant<Types...>` (C++17, header `<variant>`) is a **type-safe tagged union**: an object that holds a value of exactly one of the listed alternative types at a time, together with a record of which one. The contained value is nested within the variant object itself, so no heap allocation is involved. For a network protocol, `using Message = std::variant<Ping, Data, Close>;` says a message is one of three things, and the type system keeps track of which. ## Asking what it holds | Query | Result | |---|---| | `v.index()` | zero-based position of the active alternative (`variant_npos` if valueless) | | `std::holds_alternative<Data>(v)` | `true` if the active alternative is `Data` | | `v.valueless_by_exception()` | `true` only after a failed type-changing operation | `index()` is handy for `switch` statements and logging; `holds_alternative` reads better in an `if`. ## Reading the value 1. **`std::get_if<T>(&v)` or `std::get_if<I>(&v)`** takes a pointer to the variant and returns a pointer to the contained value, or `nullptr` if another alternative is active. It is `noexcept` and the usual non-throwing choice: `if (const Data* d = std::get_if<Data>(&m)) send(d->payload);`. 2. **`std::get<T>(v)` or `std::get<I>(v)`** returns a reference to the value and throws `std::bad_variant_access` (derived from `std::exception`) when the requested alternative is not active. 3. **`std::visit`** calls a function with whatever is active, which avoids the test-and-read pattern entirely; it gets its own treatment because the overloaded-lambda idiom has rules of its own. Getting **by type** has a precondition checked at compile time: the type must occur **exactly once** in the alternatives. For `std::variant<int, int>`, `std::get<int>(v)` is ill-formed and you must write `std::get<0>(v)` or `std::get<1>(v)`. Getting by index works for any list. ## Default construction and std::monostate A default-constructed variant holds a **value-initialized first alternative**, with `index() == 0`. Two consequences interviewers probe: - If the first alternative has no default constructor, the variant has none either. With `struct Conn { explicit Conn(int fd); };`, declaring `std::variant<Conn, int> v;` fails to compile. - To get a deliberate "nothing yet" state, put `std::monostate` first: `std::variant<std::monostate, Conn, std::string> v;` holds `monostate` at index 0. `std::monostate` is an empty class whose objects all compare equal; it exists exactly for this job. ## Pitfalls - **`get_if` wants a pointer.** `std::get_if<Data>(m)` with a variant (not `&m`) does not compile; the pointer parameter is what lets it return `nullptr`. - **Index constants drift.** Code that switches on `index()` with literal numbers silently breaks when someone reorders the alternatives; prefer `holds_alternative`, `get_if` or `visit`. - **Do not catch `std::bad_variant_access` for control flow.** If a mismatch is a normal case, test first; the exception is for a broken assumption. - **Converting construction picks a best match, and narrowing is excluded.** `Message m = Close{1000};` is clear, but `std::variant<int, double> v = some_long;` does not compile (both conversions would narrow), and `std::variant<long, long long> v = 5;` fails because both alternatives match equally well. Name the alternative with `std::in_place_type<T>` or `std::in_place_index<I>` when it is not obvious. ## Comparing and hashing Variants of the same type compare with `==`, `<` and the other relational operators (and `<=>` since C++20). The comparison looks at `index()` first: values holding different alternatives are ordered by alternative position, and only values holding the same alternative compare their contents. `std::hash<std::variant<Types...>>` is enabled when every alternative is hashable, so a variant can be a key in `std::unordered_map`. ## Why not a C union A C++ `union` stores the same bytes for several members but does not record which one is active, and reading an inactive member is the stuff of type-punning bugs covered with undefined behaviour. `std::variant` keeps the tag, runs the right constructor and destructor, and turns a wrong read into an exception or a null pointer.
- Why does std::variant<Conn, int> v; fail to compile when Conn has only an explicit Conn(int) constructor?Because the default constructor of `variant` value-initializes its first alternative and is constrained on `is_default_constructible_v` of that type. `Conn` has no default constructor, so the variant has none either. Put `std::monostate` first, reorder the alternatives so a default-constructible type leads, or always construct the variant with a value.
- When is std::get<int>(v) ill-formed even though v can hold an int?When `int` appears more than once in the alternatives, as in `std::variant<int, int>` used for two meanings. Getting by type mandates that the type occurs exactly once, so the compiler rejects it. Use `std::get<0>` and `std::get<1>`, or better, wrap the two meanings in distinct structs so the type names the meaning.
- std::get on the wrong alternative returns a default-constructed value
- std::variant allocates its active alternative on the heap
- std::get_if takes the variant by reference and returns a reference
- A default-constructed variant holds no value until you assign one
- std::variant<int, int> works with std::get<int> like any other variant