0Pricing
C++ Academy · Lesson

std::variant

A type-safe union.

A Type-Safe Union

std::variant holds exactly one value out of a fixed list of types and remembers which one. Include <variant> to use it.

#include <iostream>
#include <variant>
int main() {
    std::variant<int, double> v = 10;
    std::cout << std::get<int>(v) << "\n";
}

Assigning Different Types

You can reassign a variant to any of its alternative types. It updates which alternative is active automatically.

#include <iostream>
#include <variant>
int main() {
    std::variant<int, double> v = 5;
    v = 3.14; // now holds a double
    std::cout << std::get<double>(v) << "\n";
}

All lessons in this course

  1. Scoped enum class
  2. Unions and Their Risks
  3. std::variant
  4. std::visit
← Back to C++ Academy