Both std::variant
and std::any
are used for storing values of different types, but they serve different purposes and have different characteristics.
std::variant
is a type-safe union. It can hold a value of one of a fixed set of types, which are specified at compile-time as template arguments. The key characteristics of std::variant
 are:
On the other hand, std::any
is a type-erasing container. It can hold a single value of any type. The type of the value is erased and not known at compile-time. Key characteristics of std::any
 are:
Use std::variant
when you have a fixed set of types and want type-safety and avoid heap allocations. For example:
#include <variant>
#include <iostream>
auto Visitor{[](auto&& arg) {
constexpr bool isInt{std::is_same_v<
std::decay_t<decltype(arg)>, int>};
constexpr bool isString{std::is_same_v<
std::decay_t<decltype(arg)>, std::string>};
if constexpr (isInt) {
std::cout << "int: " << arg << '\n';
} else if constexpr (isString) {
std::cout << "string: " << arg << '\n';
}
}};
int main() {
std::variant<int, std::string> v = 42;
std::visit(Visitor, v);
}
int: 42
Use std::any
when you need to store any type and only know what type you're storing at runtime. For example:
#include <any>
#include <iostream>
int main() {
std::any a = 42;
a = std::string("hello");
std::string& s = std::any_cast<
std::string&>(a);
std::cout << s; // prints "hello"
}
hello
In summary, use std::variant
for type-safe value-based polymorphism, and std::any
for type-erasing runtime polymorphism.
Answers to questions are automatically generated and may not have been reviewed.
std::variant
Learn how to store dynamic data types in C++ using unions and the type-safe std::variant