Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2002-07-02 11:36:59


>From: "Stéphane Bronsart" <stephane.bronsart_at_[hidden]>

> I've just write it and not fully tested.
> The solution you propse work cause you use a long to test a short.
> What about test a long ?

Well, you said you wanted to be able to use casts involving the integer
types, and long is the largest signed integer. Therefore, if you use long,
any integer (except unsigned long, which may overflow) will fit in it.
Therefore, the lexical_cast will succeed, and any narrowing cast, resulting
in underflow/overflow, will be detected by the numeric_cast, and throw an
exception.

> I repeat :
> My solution is not perfect, but (or I'm wrong) work for conversion from :
> char, short, long, signed char, signed short and signed long to string and
> vice/versa.
> I don't say that this solution is magic, nor that it's has to be put in
> boost (or modify lexical_cast) but : lexical_cast has limit and/or bug in
it

Yes, your solution appear to work. However, it's neddlessly expensive, as it
essentially involves going through lexical_cast twice. Therefore, it's more
efficient to use numeric_cast, which just checks with std::numeric_limits.

However, you're right that lexical_cast doesn't check for this. Neither does
C++, in general - e.g. "long l=60000; short s=l;" compiles just fine, but
will overflow without any exception. Therefore, this is not unique for
lexical_cast. Maybe it should be documented, though, including the use
together with numeric_cast, to provide a checked cast.

If you just need a direct, checked cast between numeric types, then
numeric_cast, by itself, will do.

> signed short i = lexical_cast<signed short>("60000");
> MUST : give a correct responce (here throw an exception);

The example code I gave does just this.

> for the conversion of float/double to string, I agree my solution fail.

So does the example code I gave, but it was based on the requirement to use
integers. If other types are required, it may be changed to acconodate that,
by changing the type used internally ("long" in the example). Having an
automatic selection of this type would be more tricky, though. Especially if
it's to accomodated UDTs, as well.

Regards,

Terje


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