std::variant
std::variant<Ts...> holds exactly one value, whose type is one of the listed alternatives. It is a type-safe union: the active type is tracked, and reading the wrong alternative throws or is a compile-time miss with std::get.
Detailed Explanation
You parse a JSON field that is either an int, a string, or null. A C union can store any of those and will not stop you from writing an int and reading a string. std::variant<std::monostate, int, std::string> stores one of them and remembers which.
A variant is a value. Its size is roughly the largest alternative plus a discriminator. No heap allocation unless an alternative allocates. Default construction activates the first alternative, which is why people put std::monostate first when there is no natural default.
Change the active type by assignment: v = 42; or v = std::string{"ada"};. std::holds_alternative<T>(v) asks whether T is active. std::get<T>(v) returns a reference to the T or throws std::bad_variant_access. std::get<I>(v) uses the zero-based index. std::get_if<T>(&v) returns a pointer or nullptr and does not throw.
The tool that scales is std::visit. You pass a callable that is overloaded for each alternative. A generic lambda [](const auto& x) { ... } works when every alternative supports the body. When they do not, an overloaded visitor (a struct with several operator(), or the overloaded{...} pattern) picks the right function. After a visit, you have handled every type. Adding an alternative and compiling will fail if the visitor is exhaustive and you did not update it.
variant is the C++ sum type. Use it for:
- A result that is one of a closed set of shapes (token types in a lexer).
- A message in a state machine or a command queue.
- A column value that can be several SQL types.
Do not use it as a generic "any object". That is std::any, and it allocates and erases the type. Do not use it instead of inheritance when the set of types is open and user-defined; virtual functions exist for that. Do not use it when one field is "maybe missing"; that is optional.
Valueless-by-exception is the sharp edge. If assignment into a variant throws while constructing the new alternative, the variant can end up with no active type. valueless_by_exception() is then true, and get throws. Strong exception-safety for variant assignment is not free; types with throwing moves make this more likely. Keep alternatives nothrow-moveable when you can.
std::variant cannot hold a reference, an array, or void. It can hold T* and optional<T>. Two identical alternatives are allowed (variant<int, int>) and are distinguished only by index, which is confusing; do not do that.
Comparisons compare the index first, then the value. A variant holding alternative 0 is less than one holding alternative 1, even if the values would compare the other way as their own types.
Code Examples
#include <iostream>
#include <string>
#include <variant>
using Field = std::variant<std::monostate, int, std::string>;
void print(const Field& f) {
std::visit([](const auto& value) {
using T = std::decay_t<decltype(value)>;
if constexpr (std::is_same_v<T, std::monostate>) {
std::cout << "null\n";
} else {
std::cout << value << '\n';
}
}, f);
}
int main() {
Field f;
print(f); // prints: null
f = 42;
print(f); // prints: 42
f = std::string{"ada"};
print(f); // prints: ada
std::cout << std::get<std::string>(f) << '\n'; // prints: ada
}#include <iostream>
#include <variant>
int main() {
std::variant<int, double> v = 3;
if (auto* n = std::get_if<int>(&v)) {
std::cout << *n << '\n'; // prints: 3
}
}Common Gotchas
First alternative is the default
`variant<std::string, int> v;` default-constructs a `string`, which may allocate. Put `std::monostate` first if empty is the default.
Valueless after a throwing assignment
check `valueless_by_exception()` after operations that can throw, or keep alternatives nothrow-moveable.
`visit` with a generic lambda needs `if constexpr`
a body that calls `value.size()` will fail to instantiate for `int`. Branch on the type, or use an overloaded visitor.