Search code examples
c++stringtype-conversionstdstring

Is there any generic conversion from std::string to numeric type?


There are many ways to convert strings to numbers in C++: stoi, stod, stof, etc. Just like how std::invoke is a nice way to call any callable, I am looking for a method that converts string value to a generic numeric value.

For instance, instead of something like this:

int x = std::stoi("5");
long y = std::stol("5555555555");

Something like this:

int x = num_convert("55");
long y = num_convert("5555555555");

Is there any standard functionality for what I am trying to do?


Solution

  • This can be considered as a generic conversion:

    #include<sstream>
    
    int main() {
      int x;
      std::stringstream("55") >> x;
    
      long y;
      std::stringstream("5555555555") >> y;
    }
    

    A function can return only a single type, thus long y = num_convert("5555555555") with a regular function is impossible.

    One more hack, help the function to deduce the returned type with the unused parameter:

    #include <string>
    
    template<typename T>
    T num_convert(const char* s, const T&) {
      return static_cast<T>(std::stoll(s));
    }
    
    int main() {
      int x = num_convert("55", x);
      long y = num_convert("5555555555", y);
    }