Boost logo

Boost :

From: Beman Dawes (beman_at_[hidden])
Date: 2000-06-27 08:01:40


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.

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();
}

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

In any case, let's try to finish cast and stream_cast/convert issues and
put the headers up for formal review. If Kevlin is still busy, I will pull
the details together if we can get general agreement.

--Beman


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