|
Boost : |
From: Ed Brey (brey_at_[hidden])
Date: 2000-06-27 15:13:22
From: "Beman Dawes" <beman_at_[hidden]>
> 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.
For the non-throwing version, I'd like for the documentation to make clear a
rationale for the default initialization. Historically, default
initialization was proposed to indicate that the conversion failed. Given
the bool return value, that is no longer necessary. So now AFAICT, the only
reason is so ensure that the target is always initialized to something. And
this can be OK. I just don't want the trade-off to get lost. The trade-off
is that we are dumping the previous value for target. In the use case where
a hard-coded initialization value can be overridden by a configuration
parameter, this means that the program will have to check the result of the
conversion and set the hard-coded value then, rather than initializing the
hard-coded value up front and then ignoring conversion failures.
I personally prefer the flexability of leaving the target value in tact and
requiring that the user default initialize the target when he defines it if
default-initailize-on-failure semantics are desired. My preference isn't
all that strong, though.
If we do keep the default-initializing semantics, I'd recommend the
implementation:
template<typename Source, typename Target>
inline bool convert(const Source& source, Target& target)
{
std::stringstream interpreter;
interpreter << std::boolalpha << source >> target;
if (interpreter.good()) return true;
target = Target();
return false;
}
This avoids the extra assignment in the common case of success. This could
be significant if target is a larger class that is assignable from a stream.
Plus it enables the "stream << innies >> outies" format, which is just too
cool to pass up. :-)
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk