Boost logo

Boost :

From: Terje Slettebø (tslettebo_at_[hidden])
Date: 2002-07-02 10:33:09


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

As Björn Karlsson mentioned, this functionality can be achieved by combining
lexical_cast and numeric_cast, like this:

#include <boost/lexical_cast.hpp>
#include <boost/cast.hpp>

long l=boost::lexical_cast<long>("60000");
short s=boost::numeric_cast<short>(l); // Throws bad_numeric_cast

or even:

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

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

These components already exist in Boost, so lexical_cast doesn't have to be
changed to accomodate this. Furthermore, using numeric_cast is more
efficient, as it avoids the extra round-trip in stringstream, to do the
checking. It simply checks using std::numeric_limits.

This also means that you don't have to pay for range-checking, if you don't
need it.

Wouldn't this do what you wanted?

----- Original Message -----
From: "Stéphane Bronsart" <stephane.bronsart_at_[hidden]>
Newsgroups: gmane.comp.lib.boost.devel
To: <boost_at_[hidden]>
Sent: Tuesday, July 02, 2002 4:18 PM
Subject: [boost] lexical_cast modification (for signed bug)

> Here is my proposal for lexical_cast :
>
> template<typename Target, typename Source>
> Target lexical_cast(Source arg)
> {
> stringstream interpreter, inter2; // for out-of-the-box g++ 2.95.2
>
> Target result;
> Source copy_of_arg;
>
> if(!(interpreter << arg) || !(interpreter >> result) ||
> !(interpreter >> ws).eof())
> throw 1;
>
> if(!(inter2 << result) || !(inter2 >> copy_of_arg) )
> throw 2;
>
> if( copy_of_arg != arg ) //
> <<<<
> throw 3;
>
> return result;
> }
>
> <<<< If all is ok, normaly copy_of_arg and arg MUST be the same !!!
> If not, exception occurs.
>
> I'm not use with boost and/or library.
> If you think this solution good, ok.
> If you think you have to adapt, ok.
> If you think its bad, please tell me why.
>
> But for me, all conversion are now ok or exception is throw.
> Thus it's Ok.
>
> I'm waiting message from you.
>
> Bye.
> Steph.
>
>
>
>
> _______________________________________________
> 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