boost::any: unleash the power of C++ with Boost libraries.
The boost::any class is a generic container for a single value. It is based on the concept of discriminated types, which means it can contain values of different types but do not attempt any conversion between them (e.g. 10 is held strictly as an int and is not implicitly convertible either to “10” or to 10.0).
The indifference to interpretation and the awareness of different types make boost:any a safe generic containers of single values, with no scope for surprises from ambiguous conversions.
To use this class, just add #include <boost/any.hpp> to your program. See the example below:
To get a value from a boost::any variable, just use boost::any_cast<T>() with one of the following approaches:
Boost.Any is based on type erasure technique. On assignment of some variable of type T, Boost.Any constructs a type (e.g. holder<T>) to store a value of the specified type T, and is derived from some internal base-type placeholder.
The placeholder has virtual functions for getting std::type_info of a stored type and for cloning a stored type. When any_cast<T>() is used, boost::any checks that std::type_info of a stored value is equal to typeid(T) (the overloaded placeholder’s function is used for getting std::type_info).
Unfortunately, boost::any requires dynamic memory allocation in copy constructor and copy assignment operators and cannot be used with runtime type information (RTTI) disabled. If you are keen on performance, see the boost::variant which has not these limitations.
##Further Information
Advantages of using the C++ Boost Libraries
Boost C++ Application Development Cookbook, by Antony Polukhin