Why there is no std :: string overload for std :: to_string

The title says that everything is real. Why did they decide not to have

namespace std { std::string to_string(const std::string&) } 

overload?

I have a program that can query for some data by row index or row name; Perfect for templates. Until I try to create an error message if there is no available line:

 template <typename T> int read(T nameOrIndex) { if (!present(nameOrIndex)) { // This does not compile if T is std::string. throw std::invalid_argument("Missing row: " + std::to_string(nameOrIndex)); } } 

I could add my own overload to the std , but this is not ideal.

+5
source share
2 answers

Instead of defining your own overload that takes std::string in the std , which is a very bad solution, just do this instead:

 #include <iostream> #include <string> std::string to_string(const std::string& value) { return value; } template <typename T> void display(T value) { using namespace std; std::cout << to_string(value) << std::endl; } int main() { display("ABC"); display(7); } 
+9
source

I'm not going to guess why overloading is not part of the standard library, but here is a simple solution that you can use. Instead of std::to_string use boost::lexical_cast .

 template <typename T> int read(T nameOrIndex) { if (!present(nameOrIndex)) { throw std::invalid_argument { "Missing row: " + boost::lexical_cast<std::string>(nameOrIndex) }; } // … } 

If you don't need a Boost dependency, you can easily collapse your own function for this.

 template <typename T> std::string to_string(const T& obj) { std::ostringstream oss {}; oss << obj; return oss.str(); } 

Obviously, it is not optimized, but may be good enough for your case.

+1
source

Source: https://habr.com/ru/post/1246980/


All Articles