Boost Variant resembles union. You can store values of different types in a boost::variant.
1.
#include <boost/variant.hpp> #include <string> int main() { boost::variant<double, char, std::string> v; v = 3.14; v = 'A'; v = "Boost"; }
boost::variant is a template, at least one parameter must be specified. One or more template parameters specify the supported types.
2. accessing values in boost::variant with boost::get()
#include <boost/variant.hpp> #include <string> #include <iostream> int main() { boost::variant<double, char, std::string> v; v = 3.14; std::cout << boost::get<double>(v) << std::endl; v = 'A'; std::cout << boost::get<char>(v) << std::endl; v = "Boost"; std::cout << boost::get<std::string>(v) << std::endl; return 0; }
to display the stored values of v, use the free-standing function boost::get().