c++ – Why no std::string overload for std::to_string

c++ – Why no std::string overload for std::to_string

Rather than define your own overload taking std::string in the std namespace, 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);
}

Im not going to guess why the overload is not in the standard library but here is a simple solution 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 dont want the Boost dependency, you can easily roll your own function for this.

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

It is obviously not optimized but might be good enough for your case.

c++ – Why no std::string overload for std::to_string

Leave a Reply

Your email address will not be published. Required fields are marked *