I am wondering what the best way to implement conversion to string is for my own classes. I have searched extensively (and consulted some books), but surprisingly I have not found any recommendations anywhere. As I see it, the options are:
Inside-class definition of the cast to string:
operator std::string() const
Outside-class overloading of
std::string to_string(const Obj&)
Related to this: is it beter to declare the overload of the streaming operator << inside the class or outside?
I'd say it depends on the type of string you're trying to generate. If it's for logging and debugging, I'd probably overload <<(ostream&), provided my logging library supports streams (or can be mode to support it).
If it makes sense as a string without surprising anyone (the upcoming string_view being one example), then I'd do the operator. If it's a number type (like a big integer), or any other type that for any other reason needs to have a string representation, I'd add a ToString() function, whether member or not.
I wouldn't, however, add a std::to_string() overload, since I wouldn't want to sneak into the std namespace with my own non-standard code. Also, you can't even use it ADL contexts, since std::to_string() only takes primitive operands.
As for the <<(ostream&) operator, there's no use declaring it as a member function, since os << myObj wouldn't work. What you can do is declare it as a friend and then have its definition inside the class declaration. This, however, would make it a non-member function, because of the friend keyword. The safest bet is, usually, to declare it as a friend and the provide the implementation in a source file.
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