Making Sense of std::variant in C++: An Introductory Perspective on Holding Different Types of Values
The problem of variance in C++ variables that may take on multiple values of different data types is resolved using various mechanisms, such as std::variant , a new C++ feature in C++17. For this feature, a variable can possess a value of several types, but not more than one type at a time. In this article, welcome to the world of std::variant, and learn how it is used alongside some other useful elements like std::monostate which extend its capabilities. So let’s begin. What is std::variant? In C++, std::variant replaces the traditional union’ with a typesafe union holder which holds one of a predefined set of types. std::variantoffers the extra advantage of keeping the type that is currently held, unlikeunion’ which doesn’t keep track of its active type very handy in instances where a type will be constantly changing. suggested reads : CRTP in C++ , placement new , memory management in C++ Declaring a Variant in C++ To declare a `std::variant`, specify the possible data type