C++ Format for cout << Automatically
Asked Answered
C

2

5

If I had a simple class with two variables, x and y, and a function ToString() that returns a formatted string with the data. When I call

cout << simpleClass << "\n";

anyone know a way I could have simpleClass.ToString automatically called to return the correctly formatted string? I'm guessing there's a way to do this with operator functions, but I don't know how I would do this.

Complaint answered 21/7, 2011 at 1:30 Comment(0)
O
9

If you're asking how to define such an operator,

template<class CharT, class TraitsT>
std::basic_ostream<CharT, TraitsT>&
operator <<(std::basic_ostream<CharT, TraitsT>& os, SimpleClass const& sc)
{
    return os << sc.ToString();
}
Obtrusive answered 21/7, 2011 at 1:33 Comment(10)
+1: I like how you implemented a function which operates on all basic_ostream objects, not just coutStretchy
@ildjarn: However, I wonder how you are going to write a SimpleClass::ToString() member that would return any string requested. (Am I missing something?)Knack
@Knack : The assumption is that the user will pass in a stream compatible with the character-type of the string, otherwise there will be a compiler error (just like trying to stream a std::wstring to a std::ostream).Obtrusive
@ildjarn: My point is that in this case it makes no sense to templatify the output operator, because, thanks to the non-template member function ToString(), it would require a truly convoluted hack for this to compile with any character encoding but one.Knack
@Knack : And I fully disagree -- there's more to a stream/string type than just the character type; e.g. the stream could use a non-default TraitsT argument.Obtrusive
@ildjarn: You are right, of course, I overlooked that. OTOH, it should not be templatized on the character type, when there is support only for one character type.Knack
@Knack : I disagree with that as well; char const* and std::string both stream equally well to std::basic_ostream<char> and std::basic_ostream<wchar_t> (e.g. std::cout and std::wcout). Why should I be forced to use a narrow stream just because the character type is narrow?Obtrusive
@ildjarn: I actually had to check that std::wcout << "Hello, world!\n" compiles. I didn't know! Well, since that's really compiles, there's indeed merit in your code, and I just failed to see this. I apologize, but I honestly didn't know you can pass a narrow string to a wide stream. How do we proceed? Shall I delete my useless comments and you then delete yours?Knack
@Knack : I think the comments could be edifying for future readers, but it's up to you. :-]Obtrusive
@ildjarn: Ok, so I'll leave it.Knack
B
2

You define

std::ostream& operator <<(std::ostream&, const SimpleClass&)

to call ToString(), passing the ostream&, and return the ostream&.

Benadryl answered 21/7, 2011 at 1:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.