Boost logo

Boost :

From: scleary_at_[hidden]
Date: 2001-10-17 14:42:47

> Yes steve, i understood that.
> What is not clear to me is that an exception is
> thrown. I would have expected the convertion, the
> actual cast from any, containing 5, to const char *)
> to work.
> To me, the resulting string s should contain "5" but
> instead the exception is thown.

Oh. Sorry, I misunderstood your question.

Take a look at the beginning of the "any" docs at Kevlin's three points
under "Motivation". "any" preserves type differences (i.e., does *not*
provide automatic conversions). Conversions like what you want are supplied
by boost::lexical_cast.

There doesn't exist a class taking advantage of lexical_cast like you want
(right now, anyway -- maybe you could submit one?). Here's a simple
prototype for one: (warning: untested code :)

class variant
    std::string data;
    template <typename T>
    variant(const T & other)
    :data(boost::lexical_cast<std::string>(other)) { }
    template <typename T>
    variant & operator=(const T & other)
      data = boost::lexical_cast<std::string>(other);
      return *this;
    // Possibly add "operator T()" ???
    template <typename T>
    T as()
    { return boost::lexical_cast<T>(data); }

variant any_value;
any_value = 5;
std::string s =<std::string>();


Boost list run by bdawes at, gregod at, cpdaniel at, john at