Overloading endl

Oct 7, 2021 at 9:09pm
Does anyone have a working example of overloading std::ostream and std::streambuf?

I want to accumulate text in the streambuf until a std::endl is detected.
At that point I want to append append the accumulated text to a std::string and push the string onto a deque (without a CR).

Here's what I have so far:
1
2
3
4
5
class MyStreamBuf : std::streambuf 
{
public:
	int sync();
};


1
2
3
4
5
6
7
8
9
10
11
12
extern DIALOG dialog;		//  Global

int MyStreamBuf::sync ()
{
	const char* pb = pbase();	// Beginning of output sequence
	const char* pe = pptr();	// Current position of output sequence	
	size_t len = pe - pb;		// Length of accumulated text	

	dialog.Append_Line(pb, len);	// Append the accumulated text to the deque
	pubseekpos(0);			// Reset the output position
	return 0;			// Success
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class DIALOG : public std::ostream
{
public:
	MyStreamBuf			m_sb;

	// function that takes a custom stream, and returns it     
	typedef DIALOG& (*DIALOGManipulator)(DIALOG&);

	// take in a function with the custom signature     
	DIALOG& operator << (DIALOGManipulator manip);

        // Overloads
        friend DIALOG& operator << (DIALOG& os, LPCSTR  str);
	friend DIALOG& operator << (DIALOG& os, int val);
};


1
2
3
4
5
// take in a function with the custom signature     
DIALOG& DIALOG::operator << (DIALOGManipulator manip)
{	// call the function, and return it's value         
	return manip(*this);
}


1
2
    dialog << m_name << " can't exchange tiles." << endl;
    dialog << "Less than " << TILES_PER_HAND << " tiles remain in bag." << endl;

What's weird is the first line compiles okay.
The second line generates a ton of errors.
Intellisense highlights the << just before the endl;


2>C:\dev\scrablib\COMPUTER.cpp(51,88): error C2679: binary '<<': no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
2>c:\dev\scrabwin\DIALOG.h(33,10): message : could be 'DIALOG &DIALOG::operator <<(DIALOG::DIALOGManipulator)'
... Followed by 70 or so possible matches.


Last edited on Oct 7, 2021 at 9:10pm
Oct 8, 2021 at 12:55am
I think that foo(Base&) is not replaceable for foo(Derived &) (not sure about the return type)

so respect the signature
https://en.cppreference.com/w/cpp/io/manip/endl
typedef std::ostream& (*DIALOGManipulator)(std::ostream&);

edit: friend DIALOG& operator << (DIALOG& os, int val); ¿why friends and not simply member functions?
Last edited on Oct 8, 2021 at 12:56am
Oct 8, 2021 at 1:49am
Thanks ne555. That did the trick.

You're right, friend is not needed.
Compiles cleanly now after the addition of an overload for unsigned char type.
 
DIALOG& operator << (UCHAR c);

Topic archived. No new replies allowed.