Boost logo

Boost :

Subject: Re: [boost] [lexical_cast] A suggestion
From: Andrew Troschinetz (ast_at_[hidden])
Date: 2009-02-04 11:31:50


On Feb 3, 2009, at 3:35 PM, Vladimir Batov wrote:

> I'd like to suggest extending (no disruption to the existing
> interface/users) 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& default_value)
>
> The behavior of the latter would be to return the 'default_value' if/
> when the conversion fails. That communicates the fact of the
> conversion failure differently (without an exception thrown) as IMHO
> a conversion failure is not really that exceptional (rather common).

Last time this topic came up I took some time to modify
lexical_cast.hpp (starting from boost 1.37.0 source) to fit this
interface. I also added a specialization for boost::optional<T> that
instead of throwing bad_lexical_cast, simply returned an empty
optional type (which required rewriting optional_io.hpp, as I believe
it has a bug: https://svn.boost.org/trac/boost/ticket/2659 ).

Here's some example usage: http://codepad.org/hn6MjKjm

modified lexical_cast.hpp: http://codepad.org/JAA4Me9Q
modified optional_io.hpp: http://codepad.org/8ablH1Nq

I too would love to see these extensions to lexical_cast, but in the
meantime I've been using these modified versions. Just thought I'd
share them in case anyone else was interested.

--
Andrew Troschinetz
Applied Research Laboratories

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