Boost logo

Boost :

Subject: Re: [boost] [lexical_cast] A suggestion
From: Chris Weed (chrisweed_at_[hidden])
Date: 2009-01-13 10:50:57


On Tue, Jan 13, 2009 at 7:26 AM, Vladimir Batov <batov_at_[hidden]> wrote:
>
> I use boost::lexical_cast quite a bit. Possibly due to specifics of my task I constantly stumble upon two things:
>
> 1. It throws if/when conversion fails;
> 2. It requires the 'Target' class to be default-constructible.
>
> I'd like to suggest extending the existing
>
> template<class Target, class Source>
> Target
> lexical_cast(Source const& arg)
>
> interface with
>
> template<class Target, class Source>
> Target
> lexical_cast(Source const& arg, Target const& failure_value)
>
> The behavior of the latter would be to return the 'failure_value' if/when the conversion fails. That communicates the fact of the conversion failure differently (without an exception thrown), i.e. its usage would be as following:
>
> int value = boost::lexical_cast(some-string, -1);
> if (value == -1) conversion failed.
>
> In fact, my usage pattern is such that I often do not even need to check the success of the conversion -- if the conversion fails, the supplied failure/default value is returned/used and proceeded with.
>

This doesn't look like a good interface due to using a casted value as
a "null"-code. This code would fail when "-1" is a value of
some-string. This could lead to very big problems!
I would suggest something more like
boost::optional<int> value = boost::lexical_cast(some-string,boost::no_throw);
if(!value) conversion failed.

Chris


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