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 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:

  • 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

When to Use Dynamic Types in C++
The lesson mentions dynamic typing should be rare in C++. When is it appropriate to use void pointers or std::any?
Performance Impact of std::any
Does using std::any have a significant performance impact compared to using concrete types directly?
Storing std::any in a Container
How can I store std::any objects in a container like std::vector?
std::any and Memory Leaks
Can using std::any lead to memory leaks? How can I prevent them?
std::any and Small Object Optimization
Does std::any use small object optimization? If so, how does it work and what are the benefits?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant