Boost logo

Boost :

Subject: Re: [boost] [lexical_cast] A suggestion
From: Scott McMurray (me22.ca+boost_at_[hidden])
Date: 2009-02-06 19:27:24


On Fri, Feb 6, 2009 at 17:01, Vladimir Batov <batov_at_[hidden]> wrote:
>
> I sympathize with the idealistic desire for lexical_cast to look like the
> dynamic_cast et al. The problem is that no matter how you make lexical_cast
> look it does not do what other language-supported casts do -- dynamic_cast
> el al work with *types*, lexical_cast works with *values*. Making
> lexical_cast look like what it is not (the "real" casts) has no practical
> value and is just misleading.
>

I have no idea what you mean by dynamic_cast working with "types" not
"values". static_cast<float>(1000000000u) drastically changes the
representation and the type, just like
lexical_cast<float>("1000000000") does.

And optional<> is not that strange. The first example in its
documentation is "optional return values" (
http://www.boost.org/doc/libs/1_37_0/libs/optional/doc/html/boost_optional/examples.html#boost_optional.examples.optional_return_values
), which is exactly what

attempt_lexical_cast<T>(x) just calling lexical_cast<optional<T> >(x)
makes perfect sense to me, though it's so trivial that it seems like a
waste to provide the extra function. Having the different semantics
for the different type is just like dynamic_cast, just this one uses
optional instead of *.

One very clear use:

if (optional<int> oi = lexical_cast<optional<int> >(mystring)) {
    int i = *oi;
    ... use i ...
} else {
    ... parse failed ...
}

And if you want defaults:

int i = -1;
if (optional<int> oi = lexical_cast<optional<int> >(mystring)) {
    i = *oi;
}
... use i ...

Or, using the helper:

int i = lexical_cast<optional<int> >(mystring).get_value_or(-1);

Why is this so bad?


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