Type of std::endl

ralphmerridew's Avatar, Join Date: Feb 2007
Newbie Member
My program includes a custom class which uses operator<< similarly to an ostream. I'd like to be able to send it 'endl', but I can't find out what function I need to define to accept it.
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
endl sends a newline followed by a flush of the stream.
0
ralphmerridew's Avatar, Join Date: Feb 2007
Newbie Member
Let me rephrase:

I want to be able to have something like:

MyClass stream;
stream << std::endl;


And to do that, I need to define
operator<< (MyClass &, _____)

What goes in the blank?
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
bloank should be outstream but as far as I remember the first param should be the blank and second one your class
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
Here's a nice tutorial on operator overloading, written by a friend.
0
ralphmerridew's Avatar, Join Date: Feb 2007
Newbie Member
Let me rephrase again: I want to create a class "MyStreamLikeClass" which functions similarly to an ostream, so the following code would be legal:

MyStreamLikeClass stream;
stream << std::endl;

I need to define
MyStreamLikeClass &operator<< (MyStreamLikeClass &, _____);
where _____ is the appropriate type for endl.

shabbir's comment (did he me 'ostream' instead of 'outstream') is not what I want because I am not using the standard C++ streams. The argument which goes first is the stream class, which in my case would be MyStreamLikeClass.
0
ralphmerridew's Avatar, Join Date: Feb 2007
Newbie Member
Never mind: I managed to work it out by going over headers,

In case anybody else should ever have the same problem:


#include <iostream>

class MyStream
{
int total;
public:
MyStream() : total (0) {}
void flush() { std::cout << total << "\n"; total = 0; }
MyStream &operator<< (int i) { total = total + i; return *this; }
MyStream &operator<< (MyStream &f(MyStream &)) { return f(*this); }
~MyStream() { flush(); }
};

MyStream &endl(MyStream &f) { f.flush(); return f; }

int main (int argc, char *argv[])
{
MyStream str;
str << 1 << 2 << 3 << endl << 4 << endl << 7;
}
0
DaWei's Avatar, Join Date: Dec 2006
Team Leader
I would recommend that your version of flush incorporate cout.flush(), otherwise it can be misinterpreted by a user, at it doesn't actually flush the stream, which is the whole point of endl.