boost::variant: unleash the power of C++ with Boost libraries.
This is the second part of Storing Multiple Types Using Boost . In the previous post I introduced boost::any class and how to use it to store a single value of any type.
We have seen that it is very flexible and simple to use, and why in some circumstances it cannot be used for performance reasons. Indeed, it requires to work dynamic memory allocation and runtime type information (RTTI) enabled.
The Boost.Variant library is the rigth alternative to use in these situations. This class can store any of the types specified at compile time; it also manages in-place construction/destruction and doesn’t even require the C++11 standard.
To use this class, just add #include <boost/variant.hpp> to your program. See the example below:
To get a value from a boost::variant
boost::variant class holds an array of characters and stores values in that array. Array size is determined at compile time using sizeof() and functions to get alignment. It is extremely fast because it does not allocate memory in a heap and does not require RTTI enabled.
Boost C++ Application Development Cookbook, by Antony Polukhin