Boost logo

Boost :

From: Stéphane Bronsart (stephane.bronsart_at_[hidden])
Date: 2002-07-24 03:58:03


Hi,

A signed long can hold value from -2147483648 to 2147483647

signed long l;

1) l=lexical_cast<signed long>("2147483647"); // Ok l = 2147483647
2) l=lexical_cast<signed long>("2147483648"); // False : no exception
                                                                        //
and l = -2147483648
3) l=lexical_cast<signed long>("2147483650"); // OK exception occurs

> Why case 2 don't throw exception and case 3 yes ?
> If lexical_cast throw exption with a value 3 unit greater than the limit,
> why not with a value 1 greater than the limit ?

Kevlin say : "Some they the error is in the stream operator for long in the
STLport 4.5.3."

____________________________________________________________________________
___

"Terje Slettebø" <tslettebo_at_[hidden]> wrote in message
news:0a5901c232ec$5d7785e0$60fb5dd5_at_pc...
>From: "Stéphane Bronsart" <stephane.bronsart_at_[hidden]>

> Some week ago, I've alerted about a problem using lexical_cast with signed
> number.
>
> ex : signed int number = lexical_cast<signed int>("60000");
> return a bad value (the complement) without throwing an exception.
>
> Kevlin email me that that the real problem was certainly in the "local"
> implementation (used by iostream, thus by lexical_cast). How to solve
these
> problem. Who is responsible for that. Who will correct it ?

Like it was mentioned in that thread, you can use something like this:

template<class Target, class Source>
Target checked_lexical_cast(Source arg)
{
  long l=boost::lexical_cast<long>(arg);

  return boost::numeric_cast<Target>(l);
}

At least this works for integers. A problem here is that when it reads the
value from the string, like "60000", it doesn't know how big the value will
be, or what kind of value it is. It needs to be told that. So, above here,
"long" is used, as it should be able able to handle all integers. Then, you
may use a checked conversion like numeric_cast, to convert this to the
required type.

Anybody else have any ideas about this?

Regards,

Terje

_______________________________________________
Unsubscribe & other changes:
http://lists.boost.org/mailman/listinfo.cgi/boost


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