std::any
and std::variant
are both ways to create a variable that can hold different types, but they work quite differently:
std::any
can hold a value of any single type, and the type can be decided at runtime. It's like a type-safe void*
.
std::any a = 42;
a = "hello";// OK, a now holds a string
std::variant
holds a value that can be one of a fixed set of types, which must be specified at compile-time.
std::variant<int, string> v = 42;
v = "hello"; // OK, string is one of the types
v = 3.14; // Error: double is not one of the types
Use std::any
 when:
Use std::variant
 when:
Generally, prefer std::variant
where possible. It offers better performance and type-safety. Only use std::any when the flexibility of runtime typing is truly necessary.
Answers to questions are automatically generated and may not have been reviewed.
std::any
Learn how to use void pointers and std::any
to implement unconstrained dynamic types, and understand when they should be used