std::any vs std::variant
What's the difference between std::any and std::variant? When would I use one over the other?
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 stringstd::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 typesUse std::any when:
- The type really can't be known at compile-time
- You need to store any single value, but the type might change
Use std::variant when:
- The type can be one of a limited set of known types
- You need to store multiple types in the same variable or container
- You want the type-safety and performance benefits of knowing the types at compile-time
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.
Unconstrained Dynamic Types using Void Pointers and std::any
Learn how to use void pointers and std::any to implement unconstrained dynamic types, and understand when they should be used