Skip to content

std::variant (C++17) ​

In a Nutshell ​

A type-safe replacement for a union: it stores values of different types in the same chunk of memory and lets you access them safely by index or by type.

Header File ​

#include <variant>

Core API Cheat Sheet ​

OperationSignatureDescription
Constructorvariant()Default-constructs the variant, holding a value of the first candidate type
Assignmentvariant& operator=(T&& t)Assigns the value and switches the active alternative accordingly
Access by typetemplate<class T> T& get(variant& v)Fetches the value by type; throws an exception if the type does not match
Access by indextemplate<size_t I> T& get(variant& v)Fetches the value by index; throws an exception if the index is out of range
Safe accesstemplate<class T> T* get_if(variant* v)Fetches a pointer by type; returns nullptr on mismatch
Type checktemplate<class T> bool holds_alternative(const variant& v)Checks whether the variant currently holds the specified type
Visitortemplate<class Vis> R visit(Vis&& vis, variant& v)Passes in a callable and dispatches it to the currently active type
Current indexsize_t index() constReturns the zero-based index of the currently active type
In-place constructiontemplate<class T, class... Args> T& emplace(Args&&... args)Destroys the old value and constructs a new one in place

Minimal Example ​

C++
#include <iostream>
#include <string>
#include <variant>
// Standard: C++17
int main() {
    std::variant<int, std::string> v = 42;
    std::cout << std::get<int>(v) << '\n';
    v = "hello";
    std::cout << std::get<std::string>(v) << '\n';
    std::visit([](auto&& arg) {
        std::cout << arg << '\n';
    }, v);
}

Embedded Applicability: Medium ​

  • Compared with a bare union, it carries extra storage for the type index plus runtime check overhead
  • It spares us the error-prone job of hand-managing union dirty flags, which makes the code more robust
  • A good fit for application-layer state management or message parsing on reasonably resourced targets (e.g., SoCs with an MMU)
  • On severely constrained bare-metal targets, weigh the sizeof overhead carefully before committing to it

Compiler Support ​

GCCClangMSVC
7.15.019.10

See Also ​


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05