Boost logo

Boost Users :

From: Electric Monk (yg-boost-users_at_[hidden])
Date: 2003-04-03 20:19:22


I have a need to cast a boost::any with an arbitrary contained type to
another type, using a boost::lexical_cast for example.

Consider the following:

#include <boost/any.hpp>

class obj
{
public:
  int val0;
  double val1;

  void setval(int i, boost:any const & val)
  {
    switch (i)
    {
      case 0: val0 = boost::any_cast<int>(val); break;
      case 1: val1 = boost::any_cast<double>(val); break;
    }
  }
};

int main(int, char*[])
{
obj o;
  o.setval(0, 1);
  o.setval(1, 2);
  return 0;
}

As expected, this throws a boost::bad_any_cast() at runtime. I'd like to
write code similar to (from obj::setval above):

  case 0: val0 = boost::lexical_cast<int>(val); break;
  case 1: val1 = boost::lexical_cast<double>(val); break;

Unfortunately boost::lexical_cast doesn't handle a parameter of type
boost::any, since there isn't an overload of 'std::ostream operator <<()'
for type boost::any.

Can anyone suggest a simple way around this? My own musings on the subject
have lead me to thinking that there needs to be a simple way to extract the
contained value, or write it to a stream, without knowing its type.

The simplest method I can see would be to add a function to
boost::any::placeholder which either returns a string representation of the
held value or writes the held value to a std::basic_ostream. This should
allow a simple boost::lexical_cast conversion for boost::any to any
arbitrary type.

Comments? Have I missed anything major?

Oh, and yes, I know that this goes beyond the intent of boost::any. I could
easily create my own variant of boost::any which acts in the way I want, but
I think this kind of functionality is useful in a number of cases, so it'd
be nice to have the best solution possible... which is best discussed by the
people here, who are much better versed in the boost library than I :)

--
Corey Murtagh
The Electric Monk
"Quidquid latine dictum sit, altum viditur!"

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