RE: [Boost-Users] Problem with boost::any.

Luc Bergeron [mailto:bluc@videotron.ca] wrote:
Greets,
I'm trying to use the boost::any component but i'm having problem with it !!! I'm using it because I need a way to store parameters of different type. That real fine but I can't retrieve the value from the boost::any. This is what i've tried :
std::string GetStringFromAny(const boost::any& val) const { std::string strVal; try { strVal = boost::any_cast<std::string>(val); } catch(boost::bad_any_cast &err) { std::cerr << err.what() << std::endl; return ""; } return strVal; }
But I always have a bad_any_cast exception. From the documentation, at leats what I understand of it, "If passed a value or reference, it returns a copy of the value content if successful". Can someone point me in the right direction as to how can I extract the value within a boost::any type, I think i'm lost !!! :)
The following program works for me, without any error (using MSVC6): #include <boost/any.hpp> #include <string> #include <iostream> std::string GetStringFromAny(const boost::any& val) { std::string strVal; try { strVal = boost::any_cast<std::string>(val); } catch(boost::bad_any_cast &err) { std::cerr << err.what() << std::endl; return ""; } return strVal; } int main() { boost::any anAny( std::string("Hello, world") ); std::string converted = GetStringFromAny( anAny ); std::cout << "Converted: [" << converted << "]" << std::endl; } The output, as I expected, was: Converted: [Hello, world] Note that if I add more to main: int main() { boost::any anAny( std::string("Hello, world") ); std::string converted = GetStringFromAny( anAny ); std::cout << "Converted: [" << converted << "]" << std::endl; anAny = 23; converted = GetStringFromAny( anAny ); std::cout << "Converted: [" << converted << "]" << std::endl; } the second conversion fails. The conversion will only succeed if the type that boost::any currently holds can be implicitly converted into the type you want to retrieve. If you want to convert from (for example) an int to a string, you'll need boost::lexical_cast. -- Jim -- Jim
participants (1)
-
Jim.Hyslop