Boost logo

Boost :

From: David Abrahams (abrahams_at_[hidden])
Date: 2000-06-27 23:18:38


----- Original Message -----
From: "Beman Dawes" <beman_at_[hidden]>
To: <boost_at_[hidden]>; <boost_at_[hidden]>
Sent: Tuesday, June 27, 2000 9:01 AM
Subject: Re: [boost] Plea for addition of stream_cast

> I would like to move ahead with two versions of Kevlin's stream_cast
> concept. One which throws on errors as suggested by Steve Cleary, and one
> reports errors via bool return as suggested by Ed Brey. I modified Ed's
> code so it default initializes per Kevlin's code. The intent is that the
> two argument form can be used without checking the error return when
> default behavior on errors is desired.
>
> It seems to me these are really conversion functions, and have named them
> as such.

Isn't a cast a conversion function? I don't really see the distinction. I
thought stream_cast was a good name, though maybe it should be called
lexical_cast.

> Here's what the code looks like. (I couldn't find Steve's code so
> reimplemented it. Please review for mistakes, typos, etc.):
>
> // Based on concepts and implementations by Kevlin Henney.
> // Steve Cleary suggested throwing an exception on errors.
> // Ed Brey suggested the non-throwing version.
>
> // Throwing version
>
> template<typename Target, typename Source>
> inline Target convert(const Source& source)
> {
> std::stringstream interpreter;
> interpreter << std::boolalpha << source;
> Target result;
> interpreter >> result;
> if ( !interpreter.good() ) throw boost::whatever;
> return result;
> }
>
> // Non-throwing version with default error behavior
>
> template<typename Source, typename Target>
> inline bool convert(const Source& source, Target& target)
> {
> std::stringstream interpreter;
> interpreter << std::boolalpha << source;
> target = Target(); // error default behavior
> interpreter >> target;
> return interpreter.good();
> }

Don't you want something in here to make sure that all of the stream is
consumed during the conversion? if someone tries to convert "1sillyMessage"
to an int, it should fail, no?

> What header should these go in? They aren't casts; they are more utility
> in nature. So how about boost/utility.hpp?

Again, these can be used for casting (e.g. an int to a float). I see it as
simply a more liberal kind of cast to convert a string to an int or
vice-versa. Casting is a good metaphor here.

-Dave


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk