Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

The title says it all really. Why did they choose to not have a

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

overload?

I have an program that can query some data by row index or row name; ideal for templates. Until I try to construct an error message if a row being accessed is missing:

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 namespace but that's not ideal.

like image 235
James Avatar asked Apr 12 '16 22:04

James


2 Answers

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);
}
like image 72
Timothy Shields Avatar answered Sep 18 '22 12:09

Timothy Shields


I'm 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 don't 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.

like image 33
5gon12eder Avatar answered Sep 19 '22 12:09

5gon12eder