简体   繁体   中英

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

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.

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM