I know it seems too much Java or C#. However, is it possible/good/wise to make my own class valid as an input for the function std::to_string
?
Example:
class my_class{
public:
std::string give_me_a_string_of_you() const{
return "I am " + std::to_string(i);
}
int i;
};
void main(){
my_class my_object;
std::cout<< std::to_string(my_object);
}
If there is no such thing (and I think that), what is the best way to do it?
What's the 'best' way is an open question.
There are a few ways.
The first thing to say is that overloading std::to_string
for a custom type is not allowed. We may only specialise template functions and classes in the std
namespace for custom types, and std::to_string
is not a template function.
That said, a good way to treat to_string
is much like an operator or an implementation of swap
. i.e. allow argument-dependent-lookup to do the work.
so when we want to convert something to a string we could write:
using std::to_string;
auto s = to_string(x) + " : " + to_string(i);
assuming that x was an object of type X in namespace Y and i was an int, we could then define:
namespace Y {
std::string to_string(const X& x);
}
which would now mean that:
invoking to_string(x)
actually selects Y::to_string(const Y::X&)
, and
invoking to_string(i)
selects std::to_string(int)
Going further, it may be that you want to_string to do much the same as operator<<, so then one can be written in terms of the other:
namespace Y {
inline std::ostream& operator<<(std::ostream& os, const X& x) { /* implement here */; return os; }
inline std::string to_string(const X& x) {
std::ostringstream ss;
ss << x;
return ss.str();
}
}