Boost logo

Boost :

From: Andrey Melnikov (melnikov_at_[hidden])
Date: 2005-05-05 14:55:29


Dave Dribin wrote:
> Since it sounds like the main argument against adding a second argument
> is that it is no longer cast-like, the simplest idea is to rename
> lexical_cast so it is no longer cast-like. I was thinking convert_to
> would be nice and readable:
>
> int n = convert_to<int>("abc"); // Should throw an exception...
> bad_conversion?
> int n = convert_to<int>("abc", 0); // Should return 0
>
> string s = convert_to<string>(5);
>
> The main issue with renaming, obviously, is backward compatibility. Of
> course, there's no need to remove lexical_cast right away, or at all,
> even. Maybe make it deprecated, or at least implemented in terms of
> convert_to.

The purpose of lexical cast is conversion through serializaton and
deserialization. boost::lexical_cast is called lexical cast because it
uses STL object serialization framework based on << and >> operators.

Semantically convert_to is a different operation. Safe C++ way to do
itoa has nothing to do with serialization.

Also lexical_cast has an awful performance, because an intermediate
string stream has to be created.

I think we can leave lexical_cast alone as it is, but add separate
functions for safe conversions between ascii and binary representation
of numbers. These functions should be fast and properly named according
to their semantic. Performance requirement can also force us to
implement additional interface with error flag instead of throwing
exceptions. convert_to<int>("abc") can be so fast that in some
applications overhead of throwing an exception will be very noticeable.

Theoretically, it's possible to speed up current
boost::lexical_cast<size_t>("abc") by adding N^2 specializations for all
POD flavours. Below is a hack I use to speed up boost::date_time (it
uses boost::lexical_cast with atoi/itoa semantic internally).

What do you think about performance issues? Should they be addressed in
this and other boost libraries (like extremely slow boost::date_time and
boost::tokenizer/token_iterator), or the most users don't need higher
performance?

Andrey

-------------------

template<typename Target, typename Source>
class lexical_caster
{
public:
        static Target cast(Source arg); // old << / >>
}

template<>
class lexical_caster<unsigned short, std::string>
{
        // fast specialization using classical loop with multiplies
        // I didn't find a very fast function like atoi, but with
        // some kind of conversion failure indication
}

template<typename Target, typename Source>
Target lexical_cast(Source arg)
{
        return lexical_caster<Target, Source>::cast(arg);
}


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