Using std::variant as a type-safe union
In C++, a union type is a special class type that, at any point, holds a value of one of its data members. Unlike regular classes, unions cannot have base classes, nor can they be derived, and they cannot contain virtual functions (that would not make sense anyway). Unions are mostly used to define different representations of the same data. However, unions only work for types that are Plain Old Data (POD). If a union contains values of non-POD types, then these members require explicit construction with a placement new
and explicit destruction, which is cumbersome and error-prone. In C++17, a type-safe union is available in the form of a standard library class template called std::variant
. In this recipe, you will learn how to use it to model alternative values.
Getting ready
The std::variant
type implements a type-safe discriminated union. Although discussing these in detail is beyond the scope of this recipe, we will introduce them...