Boost logo

Boost Users :

From: Niels Dekker - mail address until 2008-12-31 (nd_mail_address_valid_until_2008-12-31_at_[hidden])
Date: 2008-07-10 13:07:10


Ferdinand Prantl wrote:
> I use boost::any for serialization and deserialization of both
> user-provided values and hard-coded constants. Stream output has to be
> done a little clumsily by a custom operator<<() which consists of a
> big if/elseif code block deciding what to do according to
> boost::any::type().

Would it be helpful to you if boost::any would have a function to
retrieve its value "as a string"? I /think/ such a function,
any::str(), could be implemented quite easily, as a pure virtual
function of any::placeholder, implemented within any::holder<ValueType>
as follows:

  virtual const std::string str() const
  {
    using any_implementation_details::operator<<;
    std::ostringstream stream;
    stream << held;
    return stream.str();
  }

The namespace any_implementation_details would have an empty default
implementation of operator<<:

 namespace any_implementation_details
 {
  template<class T1, class T2, class ValueType>
  void operator<<(std::basic_ostream<T1, T2>&, const ValueType &)
  {
    // Only called when ValueType doesn't have a better operator<<.
  }
 }

But if ValueType would have its own operator<<, the compiler would pick
that one instead.

boost::any::str() would just forward the result from placeholder::str():

  std::string str() const
  {
    return content ? content->str() : std::string();
  }

I think it would work for any type of value, including char-pointers and
std::strings. In the future it could even be used for char-arrays, when
array support is added. :-) What do you think? Would it simplify your
serialization?

> Thank you very much for your deep insight!

You're welcome :-)

Kind regards, Niels

PS, For those who missed it, there's another thread on this iussue at
the Boost developers' mailing list, "[boost] An elegant way to
initialize an instance of boost::anywith a C-style string constant",
http://thread.gmane.org/gmane.comp.lib.boost.devel/177324


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