stl · medium
std::variant & std::visit
std::variant holds one of several types and remembers which via index(). std::visit dispatches to the overload for the active type. Accessing the wrong alternative throws std::bad_variant_access — safer than a raw union, which gives undefined behavior.
🔑 Key line
std::variant is a type-safe tagged union: exactly one active alternative plus an index; std::visit dispatches on the active type; a wrong std::get throws bad_variant_access.
The code
std::variant<int, std::string, double> v = 42; // holds int, index 0v = std::string("hi"); // now holds string, index 1size_t i = v.index(); // 1
std::visit([](auto&& x) { use(x); }, v); // -> string overloadint n = std::get<int>(v); // throws bad_variant_accessWhat this lesson walks through
- 01
- 02
- 03
- 04
- 05
- 06
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of std::variant & std::visit and 100+ animated C++ interview lessons.