Subject: Re: [boost] [conversion] try_lexical_cast and 200$
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2013-12-12 02:21:32
On Thu, Dec 12, 2013 at 9:41 AM, Peter Dimov <lists_at_[hidden]> wrote:
> Antony Polukhin wrote:
>> * `try_lexical_cast` must be added or not?
> The motivation given is convincing.
> "At Facebook we've seen many instances of programs that call lexical_cast in
> a try/catch. In cases where the parsing is expected to fail (eg, an argument
> could be an int or a date) we frequently see extremely poor performance in
> multithreading. GCC is known to have poor multithreaded exception handling
> Even without the performance argument, seeing repeated occurrences of
> calling a function in a try block is a strong hint that the function perhaps
> ought to not report the error via an exception.
>> And if yes, what signature is preffered:
>> bool try_lexical_cast<Out, In>(Out&, const In&)
>> bool try_lexical_cast<Out, In>(const In&, Out&)
>> boost::optional<Out> try_lexical_cast<Out, In>(const In&)
> bool try_lexical_cast<In, Out>(const In&, Out&), I'd say. optional<> is cute
> because you can use if( auto x = try_lexical_cast<Out>(in) ), but not very
> convenient for the common case of try_lexical_cast(in1, out1) &&
> try_lexical_cast(in2, out2).
I have no strong preference, but with optional it's a little easier to
provide a default if the cast fails:
int n = try_lexical_cast< int >(str).get_value_or(-1);
But it adds a dependency on Boost.Optional. This syntax is also closer
to casts, while the two-argument version looks like an ordinary
function. If the two-argument version is chosen, maybe a better name
should be chosen, like:
template< typename From, typename To >
bool lexical_convert(From&& from, To& to);