Boost logo

Boost :

From: Dave Dribin (dave-ml_at_[hidden])
Date: 2005-05-09 16:14:48


On May 5, 2005, at 2:55 PM, Andrey Melnikov wrote:
> Semantically convert_to is a different operation. Safe C++ way to do
> itoa has nothing to do with serialization.

Then why does the lexical cast documentation specifically compare
itself to atoi and strtol:

   http://www.boost.org/libs/conversion/lexical_cast.htm

As stated in the first paragraph on the motivation:

"Sometimes a value must be converted to a literal text form, such as an
int represented as a string, or vice-versa, when a string is
interpreted as an int. Such examples are common when converting between
data types internal to a program and representation external to a
program, such as windows and configuration files."

Working with windows and configuration files, in my experience, at
least, requires handling of invalid values. They are the normal case,
not an exceptional case. And from reading the lexical_cast
documentation, you'd think this is the library to use. Apart from the
name containing "cast", lexical_cast does what I need: converting
numbers to and from strings.

> 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.

That would work, as well. But I'm thinking that convert_to would need
to fall back to lexical_cast for conversion that do not contain a
string. If we want to concentrate on the conversion to and from
strings, maybe names like string_to and to_string would be more
appropriate:

   int n = string_to<int>("50");
   int httpPort = string_to<int>("invalid conversion", 80);

And the converse:

   string message = "Connecting to server: " + host + ":" +
to_string(80);

Actually, to_string cannot have an invalid conversion case, can it? It
seems only going from a string can cause that.

And as for performance being an issue, it probably is in some cases.
In the cases where I've used string to int conversions and vice vera,
performance has not been critical and stringstreams have been just
fine, though. I started using lexical_cast because it made my
stringstream code easier to read.

-Dave


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