On this page
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
- Type-safe tagged union (C++17): Stores exactly one of the listed types inline without heap allocation.
- Dispatch exhaustively with
std::visitor inspect safely withstd::get_if<T>(&v)(unlikestd::get<T>(v)which throwsstd::bad_variant_access).
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
- tuts/cpp/stdlib/containers/expected Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/map Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/optional Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers Linked here; links to this page; shared tags: #containers, #cpp, #prog, #stdlib
- tuts/cpp/language_and_raii/templates_concepts_and_polymorphism Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/containers/array shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/span shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/string_view shared tags: #containers, #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/unordered_map shared tags: #containers, #cpp, #prog, #stdlib, #tier