Template friendly string to numeric in C++

Why there are no template functions something like:

C++17 has such generic string to number function, but named differently. They went with std::from_chars, which is overloaded for all numeric types.

As you can see, the first overload is taking any integer type as an output parameter and will assign the value to it if possible.

It can be used like this:

template<typename Numeric>
void stuff(std::string_view s) {
    auto value = Numeric{};

    auto [ptr, error] = std::from_chars(s.data(), s.data() + s.size(), value);

    if (error != std::errc{}) {
        // error with the conversion
    } else {
        // conversion successful, do stuff with value
    }
}

As you can see, it can work in generic context.


It's not a template, and it doesn't work with locales but if that isn't a show stopper then C++17 already has what you want: std::from_chars

There are overloads for all of the integer and floating-point types and the interface is the same except for the last parameters which are different for the integer and floating-point types respectively (but if the default is fine then you don't need to change anything). Because this is not a locale-aware function it is also quite fast. It will beat any of the other string to value conversion function and generally it is by orders of magnitude.

There is a very good CPPCON video about <charconv> (the header from_chars lives in) by Stephan T. Lavavej that you can watch about its usage and performance here: https://www.youtube.com/watch?v=4P_kbF0EbZM