Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2002-07-24 03:30:27


>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


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