Boost logo

Boost :

Subject: Re: [boost] [lexical_cast] A suggestion
From: Neil Groves (neil_at_[hidden])
Date: 2009-01-13 11:13:04


On Tue, Jan 13, 2009 at 3:50 PM, Chris Weed <chrisweed_at_[hidden]> wrote:

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

I prefer the original suggestion of providing a failure value for most of my
uses because:
1. Often I do not want to check an error, I have a value in mind to use in
the case of error
2. It removes the requirment for a default constructor

I see that if we need to handle an error condition then the ability to
return an optional<Target> is a good plan. Perhaps two new overloads would
be optimal?

Neil Groves

> Chris
> _______________________________________________
> Unsubscribe & other changes:
> http://lists.boost.org/mailman/listinfo.cgi/boost
>


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