Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2023-05-11 18:05:13


Robert Ramey wrote:
> We convert character arrays into built-in arithmetic types and vice versa.
> That’s it.
>
> I believe that this is what lexical_cast does. It might be different in that other
> than using arrays it uses strings.

lexical_cast can convert any streamable type to any other streamable type.
It's defined as `ss << input; ss >> output; return output;` where `ss` is
a default-constructed `std::stringstream`.

This has a number of implications. One, the conversion is locale-dependent.
Two, for conversion to string, you use lexical_cast<std::string>, which can
allocate. Three, errors are signaled via exceptions (although there's
try_lexical_convert that can avoid this.)

lexical_cast does a good job of optimizing the from_chars and to_chars
cases when it detects it can do so, but that by definition can't be better
than the programmer just calling the primitive operations from_chars
and to_chars directly, as they are (a) locale-independent, (b) non-
allocating, (c) non-throwing.

In addition to all that, from/to_chars are standard C++17, so Charconv
can be used by libraries that want to support C++11 (or 14) today, but
at the same time want to be able to switch to the standard functions
later when increasing the minimal supported standard to C++17.


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