Boost logo

Boost :

Subject: Re: [boost] [review] string convert
From: Matthew Chambers (matt.chambers42_at_[hidden])
Date: 2011-05-05 11:36:45

On 5/5/2011 10:17 AM, Jeff Flinn wrote:
> Matt Chambers wrote:
>> On 5/5/2011 6:48 AM, Stewart, Robert wrote:
>>> Your use case is the following, right?
>>> optional<int> o(try_convert_cast<int>(str));
>>> int i;
>>> if (!o)
>>> {
>>> std::cout<< "using fallback\n";
>>> i = fallback;
>>> }
>>> else
>>> {
>>> i = o.get();
>>> }
>>> That's clearly inconvenient and 5 doesn't apply because the optional won't be set if the
>>> conversion fails. To address such inconvenience, you offered convert<T>::result and
>>> pair<optional<T>,bool> has been suggested. Isn't optional redundant in the latter?
>> What happened to:
>> int i = fallback;
>> if (!try_convert_to<int>(str, i)) { cout << "using fallback"; }
>> A good postcondition is that try_convert_to does not modify i if the conversion fails. This
>> achieves the same thing and is honestly more convenient and transparent than the
>> convert<T>::result approach. I suppose you could argue that the preliminary assignment is
>> inefficient, but I can't see a reasonable objection to it. If it really must be avoided, then of
>> course for defaultable types it can look like yours (assigning the fallback in the if), but for
>> non-defaultable types there's no benefit (a default_value<T> invocation is as bad as the
>> preliminary assignment).
> How would I use this within an initializer list?

When initializing an int? Clearly in that case you can't get access to success or failure, so you
would use the throwing or non-throwing convert_cast:
foo(string s) : i(convert_cast<int>(s)) {}; // throws on failure
foo(string s) : i(convert_cast<int>(s, 42)) {}; // uses fallback value on failure


Boost list run by bdawes at, gregod at, cpdaniel at, john at