Store Different Types with std::variant

Learn to store different types with std::variant.

Introduced with C++17, the std::variant class may hold different values, one at a time, where each value must fit in the same allocated memory space. It's useful for holding alternative types for use in a single context.

Differences from the primitive union structure

The variant class is a tagged unionA tagged union, also known as a variant or discriminated union, is a data structure that can hold values of different types, with a tag or discriminator indicating the currently active type.. It differs from the primitive union structure in that only one type may be in effect at a time. The primitive union type, inherited from C, is a structure where the same datum may be accessed as different types. For example:

Get hands-on with 1200+ tech skills courses.