Boost logo

Boost :

From: Tim Shead (tshead_at_[hidden])
Date: 2002-04-02 17:28:38

If you have an object whose serialization contains whitespace, say:

class map_coordinates
   /* Other stuff here */

   friend std::ostream& operator<<(std::ostream& Stream, const
map_coordinates& RHS)
     Stream << RHS.m_latitude << " " << RHS.m_longitude;
     return Stream;

   double m_latitude;
   double m_longitude;

... and you use boost::lexical_cast to convert it to a string:

extern map_coordinates get_current_position();

widget.set_text("Position: " +

... you will (correctly) get a bad_lexical_cast exception, because the
extraction operator for the target type (std::string) only extracts
characters up to the first bit of whitespace. Converting objects to
their string representations seems to me to be a common enough scenario
to warrant their own function, such as "string_cast":

// Basically a slight modification of Kevlin Henney's lexical_cast ...

// exception used to indicate runtime string_cast failure
class bad_string_cast : public std::bad_cast
   virtual const char * what() const throw()
     return "bad string cast: source type value could not be interpreted
as a string";

template<typename SourceType>
std::string string_cast(SourceType arg)
   std::stringstream interpreter;

   if(!(interpreter << arg))
     throw bad_string_cast();

   return interpreter.str();

Of course, there's room here for supporting wide strings, etc. Has
anything such as this been considered before?

Timothy M. Shead

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