On this page
  1. std::variant
  2. Overview
  3. Notes & Pitfalls
  4. Example

std::variant

Prev: std::map | Up: containers | Next: std::expected
Rel: Templates, Concepts & Polymorphism, std::optional
Ref: cppreference — std::variant
Tags: #public #prog #cpp #stdlib #containers #tier/standard


Overview

std::variant<Ts...> (<variant>, C++17) is a type-safe, stack-allocated tagged union (sum type) holding one value from a closed set of alternatives—an ergonomic, zero-heap-allocation alternative to virtual inheritance hierarchies for closed sets of types.

Notes & Pitfalls

Example

#include <cassert>
#include <string>
#include <variant>

int main() {
    std::variant<int, std::string> v = 42;
    assert(std::holds_alternative<int>(v) && std::get<int>(v) == 42);
    v = std::string("ok");
    if (auto* s = std::get_if<std::string>(&v)) {
        assert(*s == "ok");
    }
}

Linked from

Related notes