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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With