|
-
May 9th, 2012, 08:55 PM
#3
Re: Inherit from cout - how to override "<<" operator & forward to base
 Originally Posted by monarch_dodra
You can always define an operator<< for your myOutput, that just calls the displayheader, before forwarding to ostream<<:
. . .
I'm not 100% sure of the impact afterwards for user writen ostream operators, but I think it should be fine.
Awesome, thanks! This seems to work well.
I'd also like to make displayHeader() a private function, but it isn't critical, and I can live without it. Is there an easy way to do so? The following code repeatedly runs displayHeader() on my system, deciding that displayedHeader is always false, until the program runs out of memory/hits its maximum allowed memory size. (Without the added red template/friend lines in the class, it runs flawlessly.) I'm assuming I must be triggering an object copy so the original bool is never modified, or something like that, although I can't imagine why it's doing this.
I realize I left displayHeader() public in my example, just wanted to illustrate that adding two lines by themselves caused the issue.
I'm pretty sure the cause is that I don't understand something related to template friend functions, so I doubt the compiler has anything to do with it, but I do run a SVN source build of gcc to keep up with their c++11 implementation. EDIT: Recompiled using system's original gcc 4.1.2, and had the same unexpected behavior.
Code:
#include <iostream>
using namespace std;
class myOutput : public ostream {
public:
myOutput()
: ostream(cout.rdbuf())
, displayedHeader(false)
{ }
void displayHeader()
{
if(false == displayedHeader)
{
*this << "HEADER" << endl;
displayedHeader = true;
}
}
template <typename T>
friend myOutput& operator<<(myOutput& myo, const T& v);
private:
bool displayedHeader;
};
template <typename T>
myOutput& operator<<(myOutput& myo, const T& v)
{
myo.displayHeader();
static_cast<std::ostream&>(myo) << v;
return myo;
}
int main() {
myOutput output;
//output.displayHeader(); // <-- I want this line to go away
output << "Hello" << endl; // <-- By having this line call displayHeader()
output << "Hello, again" << endl; // <-- and likewise this one, but it will see displayedHeader is true
}
Last edited by darlingm; May 9th, 2012 at 08:59 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|