What is boost::any  :

boost::any is a class from Boost::any Library. It provides the ability to store arbitrary information in a variable in C++.

What to include :

Header File – “boost/any.hpp”.

What can be stored in boost::any :

Anything that is copy constructable like,

  • Built-in data types i.e. int, char, bool and std::string etc.
  • User defined data types that has copy constructor.

How to convert back from boost::any to other type :

To convert boost::any to any other type boost::any_cast is used.

What if casted into wrong type :

It will cause boost::bad_any_cast exception,
For Example,

How to avoid boost::bad_any_cast but still check wrong typecasting :

If actual value of variable inside boost::any is not matched with casting parameter then it will return error.

Useful member functions :

1.)  empty():

Tells if variable is empty or not. Return type is bool.

2.)  type():

Returns the std::type_info, that cab be used to fetch the type information of the value it contains.

When not to use boost::any :

In time critical code because it internally uses RTTI, whis is slow.

Join LinkedIn Group of Python Professional Developers who wish to expand their network and share ideas.

You can also follow us On Twitter :

Click Here to Subscribe for more Articles / Tutorials like this.