Modern C++ › C++17
std::variant and std::any
Type-safe unions, std::visit and type erasure.
Explanation
std::variant<Ts...> is a type-safe union: at any moment it holds exactly one value of one of the listed types, and it always knows which. Unlike a C union, it constructs and destroys the active member properly, and misuse is detected.
Access it with:
std::get<T>(v)/std::get<I>(v): throwsstd::bad_variant_accessif wrong;std::get_if<T>(&v): returns a pointer, ornullptrif wrong;std::holds_alternative<T>(v);std::visit(visitor, v): calls the visitor with whichever alternative is active; the compiler checks that every type is handled.
std::any holds a value of any copyable type (type erasure); retrieve it with std::any_cast<T>. It is flexible but dynamically typed and slower. Prefer variant when the set of types is known.
std::monostate is an empty type that makes a variant default-constructible when the first alternative is not.
Example
#include <any>
#include <iostream>
#include <string>
#include <variant>
#include <vector>
using Value = std::variant<int, double, std::string>;
struct Printer { // visitor: one overload per alternative
void operator()(int i) const { std::cout << "int " << i << "\n"; }
void operator()(double d) const { std::cout << "double " << d << "\n"; }
void operator()(const std::string& s) const { std::cout << "string " << s << "\n"; }
};
// overloaded lambdas: a common helper
template <typename... Fs> struct overloaded : Fs... { using Fs::operator()...; };
template <typename... Fs> overloaded(Fs...) -> overloaded<Fs...>;
int main() {
std::vector<Value> values{42, 3.14, std::string("hello")};
for (const auto& v : values)
std::visit(Printer{}, v);
for (const auto& v : values) {
std::string text = std::visit(overloaded{
[](int i) { return "i:" + std::to_string(i); },
[](double d) { return "d:" + std::to_string(d); },
[](const std::string& s) { return "s:" + s; }
}, v);
std::cout << text << "\n";
}
Value v = 10;
std::cout << std::holds_alternative<int>(v) << " " << v.index() << "\n"; // 1 0
if (auto* p = std::get_if<int>(&v)) std::cout << *p << "\n"; // 10
try { std::get<std::string>(v); }
catch (const std::bad_variant_access&) { std::cout << "wrong type\n"; }
std::any a = 5;
a = std::string("now a string");
std::cout << std::any_cast<std::string>(a) << "\n";
std::cout << a.type().name() << " " << a.has_value() << "\n";
try { std::any_cast<int>(a); }
catch (const std::bad_any_cast&) { std::cout << "bad_any_cast\n"; }
return 0;
}
Common pitfalls
- A
variantis as large as its largest alternative (plus a tag); not free for big types. visitrequires the visitor to handle all alternatives and return the same type from each; a missing overload is a compile error (a good thing).- A variant can become
valueless_by_exceptionif constructing a new value throws during assignment. anyrequires copy-constructible types and may allocate; avoid it in performance-critical code.- Two alternatives of the same type make
get<T>ambiguous; use the index form.
Legacy vs modern
C++98 used a plain union (unsafe, no non-trivial members), boost::variant/boost::any, or a class hierarchy with virtual functions plus dynamic_cast. variant is closed (all types known) and non-intrusive; virtual functions are open (new subclasses can be added later), so each has its place.
Exercises
1. Which is safer to read a value if you're not sure of the type: std::get<T> or std::get_if<T>?
get_if returns a null pointer you can test; get throws std::bad_variant_access.