Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template friendly string to numeric in C++

In C++ standard library there are functions to convert from string to numeric types:

stoi stol stoll stoul stoull stof stod stold 

but I find it tedious to use them in template code. Why there are no template functions something like:

template<typename T> T sto(...) 

to convert strings to numeric types?

I don't see any technical reason to not have them, but maybe I'm missing something. They can be specialised to call the underlying named functions and use enable_if/concepts to disable non numeric types.

Are there any template friendly alternatives in the standard library to convert string to numeric types and the other way around in an efficient way?

like image 219
Mircea Ispas Avatar asked Feb 19 '20 13:02

Mircea Ispas


People also ask

Can we use stoi in C?

What Is stoi() in C++? In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings. The stoi() function is relatively new, as it was only added to the language as of its latest revision (C++11) in 2011.

What is Atoi and stoi?

Using atoi() First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.


1 Answers

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.

like image 104
Guillaume Racicot Avatar answered Sep 22 '22 06:09

Guillaume Racicot