std::variant
Learn how to use std::variant in C++17 to store and manage data with multiple possible types safely. Understand accessing values, handling exceptions, and applying std::visit for flexible operations. This lesson helps you work with type-safe unions to optimize your C++ code.
We'll cover the following...
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 ...