Boost logo

Boost :

From: dan_at_[hidden]
Date: 2000-06-28 09:29:43


>>>>>>>>>>>>>>>>>> Original Message <<<<<<<<<<<<<<<<<<

On 6/27/00, 10:18:38 PM, David Abrahams <abrahams_at_[hidden]> wrote
regarding Re: [boost] Plea for addition of stream_cast:

> 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?

Yesterday I tried to get this working with gcc 2.95.2. Since the current
gcc library doesn't have stringstream, I had to use strstream. In the
process, I saw the problem you describe above. So this is the version I
came up with:

    template<typename Target, typename Source>
    inline Target stream_convert(const Source& source)
    {
        std::strstream interpreter;
        interpreter << source;
        Target result;

        interpreter >> result;
        if ( !interpreter.good() || interpreter.rdbuf()->in_avail() )
        {
            string errmsg = string("Unable to convert: ") +
                            interpreter.str() +
                            " to type " + typeid(Target).name();
            throw std::domain_error(errmsg);
        }

        return result;
    }

    template<typename Source, typename Target>
    inline bool stream_convert(const Source& source, Target& target)
    {
        std::strstream interpreter;
        interpreter << source;
        interpreter >> target;
        return interpreter.good() && !interpreter.rdbuf()->in_avail();
    }

In the second version I prefer not to default initialize the target
parameter.

--Dan Nuffer
dan at byu dot edu


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