Boost logo

Boost Users :

From: Michael B. Edwin Rickert (panda_at_[hidden])
Date: 2005-06-02 18:58:45


ian whittley wrote:

>>> int to(std::string const& arg, Type2Type<int> const&)
>>> {
>>> return atoi(arg.c_str());
>>> }
>>
>>
>> This won't reflect the global C++ locale.
>
>
> heh - i'm afraid i don't understand what you mean by that :) is it
> possible to rectify said problem as it would be nice to have a generic
> way of handling conversions without the overhead of having to use
> stringstreams all of the time.

What's being said is that your example using atoi is not generic - it
will behave incorrectly for some other languages - atoi only handles the
(latin? not a translations expert) characters 0-9, and won't be able to
convert languages which use different characters for their numbers
(further, it's got no error detecting, so it won't throw a
boost::bad_lexical_cast when the string isn't convertable into the
destination type).

Making this truely generic - that is, so that it will work with C++
locales - is easiest done with stringstreams. You might be able to make
some micro-optimizations by directly using locales, but most projects
don't have their main bottleneck in converting to/from strings. That is,
most developers have no incentive to add such micro-optimizations in.
The fact that your optimizer probably eliminates a lot (most? all?) of
the overhead that's possible to eliminate when using locales means
there's even less incentive.

Finally, if one truely does have their worst bottleneck as this
conversion area, they're probably better off using a project-tailored
solution which can make assumptions for optimization purpouses (e.g.
atoi can be used if you're only going to be dealing with 0-9 for digits
and don't need error handling).


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net