There is no to_string for basic string. It would have nothing to do.
After Benjamin Lindley's suggestion I would consider the following design, use to_string but provide default template:
#include <iostream>
#include <string>
struct Type {
explicit operator std::string() const{
return std::string("I am type");
}
};
namespace std {
template <typename T>
string to_string(const T& value) {
return string(value);
}
}
int main(int argc, char **argv) {
// this is what would be in class
Type x;
std::string private_string_field;
private_string_field = std::to_string(42);
std::cout << private_string_field << std::endl;
private_string_field = std::to_string(x);
std::cout << private_string_field << std::endl;
return 0;
}
By default it tries to cast the operand to a string. This way custom types can provide their own conversion. Alternative design would be to internally use stringstream and operator<< for conversions, like this:
#include <iostream>
#include <string>
#include <sstream>
struct Type {
friend std::ostream& operator<<(std::ostream& out, const Type& value){
return out << "Type through operator<<";
}
};
template <class T>
std::string to_str(const T& value) {
std::string ret;
std::ostringstream ss;
ss << value;
ret = ss.str();
return ret;
};
int main(int argc, char **argv) {
// this is what would be in class
Type x;
std::string private_string_field;
private_string_field = to_str(42);
std::cout << private_string_field << std::endl;
private_string_field = to_str(x);
std::cout << private_string_field << std::endl;
return 0;
}
to_stringoverloaded forstd::string, but... why are you using it in the code above? Theoperator<<can take care of printing anything for whichto_stringis defined with a lower cost (no need to go through an intermediatestd::string)cout. In fact, i need to store it somewhere and print it for later. inside a log file.