Mailing List wrote:
Greetings all, as I'm new to this list, I'll keep my query short.
It was suggested to me to use boost::any to store numeric values of whatever type (int, float, double, etc) so that I could use one std::list to store multiple values.
I've looked through the header (any.hpp) and I admit it's a little hard for me to follow. I'm not what you'd call a superprogrammer... yet. :)
I understand how to store a value in the boost::any object, but I'm not clear on how one would get that value back later (for display on screen, etc).
Example:
boost::any value1; boost::any value2; boost::any value3;
value1 = 127.915; value2 = 17; value3 = value1.getwhatevervalue() + value2.getwhatevervalue();
Boost.Any isn't a panacea. It won't automatically compute the type for
you and 'just do the right thing'. You're essentially looking for
'resultof' which doesn't exist in c++ yet.
With Boost.Any you have to explicitly specify the return type. The
tools to use are boost::any::type and boost::any_cast.
boost::any const value1(float(127.915));
if (value1.type() == typeid(float)) ...
float result = boost::any_cast<float>(value1);
The latter will throw a bad_any_cast exception if you attempt to cast
to anything other than the stored type.
I've coded up your example code below. Not pretty, but does seem to do
the right thing.
HTH,
Angus
#include