Boost logo

Boost :

From: Kevlin Henney (kevlin_at_[hidden])
Date: 2005-05-07 03:50:04

In message <2360aa6f4e6f12532502448436b50451_at_[hidden]>, Dave Dribin
<dave-ml_at_[hidden]> writes
>> I'd be interested to hear your ideas.
>Since it sounds like the main argument against adding a second argument
>is that it is no longer cast-like, the simplest idea is to rename
>lexical_cast so it is no longer cast-like. I was thinking convert_to
>would be nice and readable:
> int n = convert_to<int>("abc"); // Should throw an exception...
> int n = convert_to<int>("abc", 0); // Should return 0
> string s = convert_to<string>(5);
>The main issue with renaming, obviously, is backward compatibility. Of
>course, there's no need to remove lexical_cast right away, or at all,
>even. Maybe make it deprecated, or at least implemented in terms of

I think that as a named entity, lexical_cast is fairly well settled, so
I am not sure that it could be replaced without a proper deprecation
plan. Given the less frequent need for the defaulted form, I am not sure
that such a significant is easily justified.

However, when I consider what the most common use of a defaulted value
would likely be, based on my own experience of similar features, other
library designs and indeed your example above, it appears that in the
event of non-conversion the explicitly default constructed value of the
target type is the most common use. Creating an interface for that would
be somewhat easier.

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

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


   Kevlin Henney                   phone:  +44 117 942 2990
   mailto:kevlin_at_[hidden]     mobile: +44 7801 073 508        fax:    +44 870 052 2289
   Curbralan: Consultancy + Training + Development + Review

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