Boost logo

Boost Users :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2002-10-11 08:34:27


On Friday 11 October 2002 09:05 am, Luc Bergeron wrote:
> 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 !!! :)

This code is correct AFAICT. Are you sure that the boost::any actually has a
std::string in it? It's a very common mistake to try to test a routine like
this with:

  GetStringFromAny("foo")

The type of "foo" is const char*, not std::string.

        Doug


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net