Boost logo

Boost :

From: Moore, Paul (paul.moore_at_[hidden])
Date: 2000-06-08 08:55:01


From: Ed Brey [mailto:brey_at_[hidden]]
>
> template<typename Source, typename Target>
> inline bool stream_cast(const Source& source, Target& target)
> {
> std::stringstream interpreter;
> interpreter << std::boolalpha << source;
> interpreter >> target;
> return interpreter.good();
> }

I don't have the standard to hand, just now, so this is just a note of
caution. Is there any possibility that a failure could leave target
undefined? If so, we need to protect so that unchecked cases like

    int n = 12;
    stream_cast(argv[1], n);

work as expected (default to 12 in case of failure).

Possible failure modes may be:

1. The << fails, when we should do an if (!interpreter.good()) return false;
to avoid filling target from a stream in undefined state.
2. The >> fails, which is only a problem if there is a failure which could
leave target changed. To fix this requires extracting to a temporary, and
then copying.

I suspect that the standard makes stream operations safe, so that this sort
of checking isn't needed. But I can never remember for sure, and I'm always
paranoid about these things...

Paul.


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