The std::variant
If we can trade off the ability to store any type in the container and, rather, concentrate on a fixed set of types declared at the container initialization, then std::variant
is a better choice.
The std::variant
has two main advantages over std::any
:
- It does not store its contained type on the heap (unlike
std::any
) - It can be invoked with a polymorphic lambda, meaning you don't explicitly have to know its currently contained type (more about this in the later sections of this chapter)
The std::variant
works in a somewhat similar manner to a tuple, except that it only stores one object at a time. The contained type and value is the type and value you assigned it last. Look at the following image:

Tuple of types versus variant of types
Here's an example of std::variant
usage:
using VariantType = std::variant<int, std::string, bool>; auto v = VariantType{}; // The variant is empty v = 7; // v holds an int v = std::string{"Bjarne"}; // v holds a std::string, the integer...