std::variant

The last part of this section deals with std::variant which allows us to create a variable from any of the types specified in the std::variant container.

std::variant is a type-safe union. An instance of std::variant has a value from one of its types. The type must not be a reference, array or void. A std::variant can have a type more than once. A default-initialised std::variant is initialised with its first type; therefore, its first type must have a default constructor. By using var.index you get the zero-based index of the alternative held by the std::variant var. var.valueless_by_exception returns false if the variant holds a value. By using var.emplace you can create a new value in-place. There are a few global functions used to access a std:variant. The function template var.holds_alternative lets you check if the std::variant holds a specified alternative. You can use std::get with an index and with a type as argument. By using an index, you will get the value. If you invoke std::get with a type, you only will get the value if it is unique. If you use an invalid index or a non-unique type, you will get a std::bad_variant_access exception. In contrast to std::get which eventually returns an exception, std::get_if returns a null pointer in the case of an error.

The following code snippet shows you the usage of a std::variant.

Get hands-on with 1200+ tech skills courses.