🆕Go deeper — read the bookstd::variant: type-safe state machines— runnable code & full walkthrough →

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 0
v = std::string("hi"); // now holds string, index 1
size_t i = v.index(); // 1
std::visit([](auto&& x) { use(x); }, v); // -> string overload
int n = std::get<int>(v); // throws bad_variant_access

What this lesson walks through

  1. 01
  2. 02
  3. 03
  4. 04
  5. 05
  6. 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.

← Previous
std::string_view & Dangling
Next →
Small String Optimization (SSO)