Caution with these functions: in most cases you need to check not only the error code, but also the `ptr` in the result.
Otherwise you end up with `to_int("0x1234") == 0` instead of the expected `std::nullopt`, because these functions return success if they matched a number at the beginning of the string.
I wonder why it is called `from_chars` and not `to_number` or similar. It's obvious what you are converting from, because you have to write down the argument `from_chars(someString)`, but you don't see what is coming out.
Example from the website:<p><pre><code> const std::string str { "12345678901234" };
int value = 0;
std::from_chars(str.data(),str.data() + str.size(), value);
</code></pre>
On the third line: Why can I just pass in `value` like this? Shouldn't I use `&value` to pass in the output variable as a reference?
Note that this won't work (AFAICT) with Unicode strings and non-western-arabic digits, e.g.:<p><pre><code> std::u8string_view chars{ u8"۱۲۳٤" };
int value;
enum { digit_base = 10 };
auto [ptr, ec] = std::from_chars(
chars.data(), chars.data() + chars.size(), value, digit_base);
return (ec == std::errc{}) ? value : -1;
</code></pre>
will fail to compile due to pointer incompatibility.
Whoever introduced the rule to automatically delete :: in titles on a hacker site should be made to rethink their decisions. Its a silly rule. It should go.
<i>Wasn’t the old stuff good enough? Why do we need new methods? In short: because from_chars is low-level, and offers the best possible performance.</i><p>That sounds like marketing BS, especially when most likely these functions just call into or are implemented nearly identically to the old C functions which are already going to "offers the best possible performance".<p><i>I did some benchmarks, and the new routines are blazing fast![...]around 4.5x faster than stoi, 2.2x faster than atoi and almost 50x faster than istringstream</i><p>Are you sure that wasn't because the compiler decided to optimise away the function directly? I can believe it being faster than istringstream, since that has a ton of additional overhead.<p>After all, the source is here if you want to look into the horse's mouth:<p><a href="https://raw.githubusercontent.com/gcc-mirror/gcc/master/libstdc%2B%2B-v3/include/std/charconv" rel="nofollow">https://raw.githubusercontent.com/gcc-mirror/gcc/master/libs...</a><p>Not surprisingly, under all those layers of abstraction-hell, there's just a regular accumulation loop.