Boost logo

Boost :

Subject: Re: [boost] [conversion] try_lexical_cast and 200$
From: Peter Dimov (lists_at_[hidden])
Date: 2013-12-12 10:10:58


Krzysztof Czainski wrote:
> > bool parse( X& x, std::string a, std::string b )
> > {
> > return try_lexical_cast( a, x.a ) && try_lexical_cast( b, x.b );
> > }
>
> True, but I don't think you should leave it that simple. When parsing of a
> succeeds, and parsing of b fails, you get x with new value of a, and old
> value of b.

Actually you get an unspecified value in x.b, I think. Which is mirrored in
what parse does - you get an unspecified value in x when it fails. If you
want a strong guarantee:

bool parse( X& x, std::string a, std::string b )
{
    X x2;

    if( try_lexical_cast( a, x2.a ) && try_lexical_cast( b, x2.b ) )
    {
        x = x2;
        return true;
    }
    else
    {
        return false;
    }
}

Note that try_lexical_cast providing that same strong guarantee of leaving
"out" untouched on failure doesn't simplify the implementation of the strong
parse.


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