Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the typical usage of boost any library?

Tags:

What are the advantages of using boost.any library ? Could you please give me some real life examples ? Why the same functionality couldn't be achieved by having some generic type in the root of object's hierarchy and creating containers with that base type ?

like image 930
Konstantin Avatar asked Apr 23 '09 09:04

Konstantin


People also ask

How does boost any work?

The key difference between boost::any and boost::variant is that any can store any type, while variant can store only one of a set of enumerated types. The any type stores a void* pointer to the object, as well as a typeinfo object to remember the underlying type and enforce some degree of type safety.

Which data types are used in boost libraries?

The Boost PP library supports four individual high-level data types. These are arrays, lists, seqs, and tuples.

What is boost any?

The boost::any class (based on the class of the same name described in "Valued Conversions" by Kevlin Henney, C++ Report 12(7), July/August 2000) is a variant value type based on the second category. It supports copying of any value type and safe checked extraction of that value strictly against its type.

What is boost variant?

boost::variant is defined in boost/variant. hpp . Because boost::variant is a template, at least one parameter must be specified. One or more template parameters specify the supported types. In Example 24.1, v can store values of type double , char , or std::string .


2 Answers

boost::any will happily store ints and floats, types that clearly have no base classes. A real-life example where you can use it is a virtual machine for a high-level interpreted language. Your "function" objects will need an array of arguments. This can easily be implemented with a std::list<boost::any> behind the scenes.

like image 50
MSalters Avatar answered Sep 22 '22 15:09

MSalters


I consider that Boost.Variant should always be preferred as it's non-intrusive and still calls for very structured programming.

But i guess the main idea behind boost.any is to provide the equivalent of java and c# object types. It's a way of saying "yes we can" ! :-)

like image 40
Benoît Avatar answered Sep 22 '22 15:09

Benoît