Boost logo

Boost :

From: Kevlin Henney (kevlin_at_[hidden])
Date: 2005-05-12 09:05:36


In message <c36e3cc4d205f62b0ca8f74dfe7ca778_at_[hidden]>, Dave Dribin
<dave-ml_at_[hidden]> writes
>>
>> There are essentially three practical options for doing this, as I
>>see it (a couple of others come to mind, but don't qualify as being
>>in line with the existing design):
>>
>> (1) Provide a wrapper type for the source on which lexical_cast is
>>overloaded and will handle non-conversion separately, eg
>>lexical_cast<T>(defaulted(a)) or lexical_cast<T>(nonthrowing(a)).
>>
>> (2) Specify a target type that indicates a non-throwing outcome. The
>>following suggestion has come to me from a colleague of Thomas Witt's:
>>lexical_cast< optional<T> >(a).
>>
>> (3) Define another cast-like function that is specifically named, eg
>>nothrow_lexical_cast<T>(a).
>>
>> In terms of simplicity and directness my preference is for (3),
>>although I am not wed to the name. I would be interested to hear any
>>thoughts on this.
>
>Personally, I think there is a need to to specify the default value,
>rather than rely on the default constructed value. For example:
>
> int httpPort = convert_to<int>(aString, 80);
>
>Maybe that can be done in similar vain to (1) or (2):
>
> int httpPort = lexical_cast<int>(default_value<int>(aString, 80));
>
>I don't know templates well enough to know if that's possible. Seems
>like the implementation would need to convert 80 into a string, and
>then back to an int, though, as default_value would need to return a
>string in the above example, right?

I think that the optional approach (2) would be more appropriate if this
proves to be a killer need. It is lighter in weight in terms of syntax
and implementation, and is ultimately more general purpose.

However, the example above doesn't seem to be quite the killer example
given that 0 is readily identifiable as an inappropriate port number.
Yes, it's a convenience, but the convert_to (or perhaps convert_else)
syntax is simpler than using either (2) or (3).

Kevlin

-- 
____________________________________________________________
   Kevlin Henney                   phone:  +44 117 942 2990
   mailto:kevlin_at_[hidden]     mobile: +44 7801 073 508
   http://www.curbralan.com        fax:    +44 870 052 2289
   Curbralan: Consultancy + Training + Development + Review
____________________________________________________________

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