Skip to content

std::variant (C++17)

In a Nutshell

A type-safe alternative to a union that stores values of different types in the same memory location, accessible via index or type-safe access.

#include <variant>

Core API Cheat Sheet

OperationSignatureDescription
Constructorvariant()Default constructs, holding a value of the first candidate type
Assignmentvariant& operator=(T&& t)Assigns a value and switches to the corresponding type
Access by Typetemplate<class T> T& get(variant& v)Retrieves value by type, throws exception if type does not match
Access by Indextemplate<size_t I> T& get(variant& v)Retrieves value by index, throws exception if index is out of bounds
Safe Accesstemplate<class T> T* get_if(variant* v)Retrieves pointer by type, returns nullptr if no match
Type Checktemplate<class T> bool holds_alternative(const variant& v)Checks if the variant currently holds the specified type
Visitortemplate<class Vis> R visit(Vis&& vis, variant& v)Passes a callable object, automatically dispatches 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 value in-place

Minimal Example

cpp
#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 to a bare union, it implies overhead for storing a type index and runtime checks.
  • Avoids the risk of errors associated with manually managing union dirty flags, improving code robustness.
  • Suitable for application-layer state management or message parsing in resource-rich environments (e.g., SoCs with MMUs).
  • In extremely constrained bare-metal environments, we recommend evaluating the sizeof overhead before use.

Compiler Support

GCCClangMSVC
7.15.019.10

See Also


部分内容参考自 cppreference.com,采用 CC-BY-SA 4.0 许可

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05