CKTIS / C++
std::variant — one of a fixed set of alternative types
std::variant stores a value of one of the alternatives specified by its template parameters and manages that value's lifetime. It models data such as “number or text” and provides checked ways to inspect and handle the active alternative.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <variant>
std::variant<Types...> value;
std::get<T>(value);
std::get_if<T>(&value);
std::visit(visitor, value);std::variant<Types...> from <variant> represents a closed set of alternative types. Its contained value is nested within the object; only one alternative is active at a time, except for the valueless state described below. Default construction value-initializes the first alternative and requires that alternative to be default-constructible. A first alternative of std::monostate can represent an intentional empty state.
index() returns the zero-based index of the active alternative. std::get<T>(value) returns a reference if the alternative of type T is active. It throws std::bad_variant_access if a different alternative is active or if no alternative is active. std::get_if<T>(&value) returns a pointer or nullptr, without throwing. Type-based access requires that type to occur exactly once in the alternative list; for repeated types, use index-based access such as std::get<0>(value).
std::visit(visitor, value) invokes a callable on the active value. The callable must handle every alternative; for the shown call form, all possible results must have the same type and value category. Assignment or emplace can change the active alternative. An exception during some such operations can leave the object valueless: then valueless_by_exception() returns true, index() returns std::variant_npos, and both std::get and std::visit throw std::bad_variant_access. This differs from holding std::monostate.
The example first reads an int, then replaces it with a std::string and handles the value through std::visit. This entry targets C++23; that standard reflects the repository compiler flag, not an attested production runtime. The source is an evolving working draft and may also contain later features.
Examples
#include <iostream>
#include <string>
#include <variant>
int main() {
std::variant<int, std::string> value{42};
if (const auto* number = std::get_if<int>(&value)) {
std::cout << *number << '\n';
}
value = std::string{"ready"};
std::cout << value.index() << '\n';
std::visit([](const auto& item) {
std::cout << item << '\n';
}, value);
}
Result
42 1 ready
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.