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

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.