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

Here's some example usage:

modified lexical_cast.hpp:
modified optional_io.hpp:

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, gregod at, cpdaniel at, john at