inheriting ostream

E

enzo

hi all!

i need in my libraries a class to deal with messages.

I did:

class messenger
{
public:
messenger(const char* p, ostream& p_s) : m(p), m_stream(p_s)
{
}

string out()
{
m_s << m;
return m;
}

messenger&
operator << (const char* p)
{
m_s << p;
return *this;
}

private:
string m;
ostream& m_stream;
};


this class let me do:

int main()
{
messenger l(¨hallo world¨, cout);
l.out();
l << ¨hallo again¨;
return 1;
}

but i can't do:

l << endl;

i tried to change to :

class messenger : public ostream

but doesn't compile.

What am i doing wrong??

Thanks
 
J

Jacques Labuschagne

enzo said:
l << endl;

Because std::endl is a function, not a const char*. Just add this:

message& operator<< (ostream& (*f)(ostream&)){
m_s << f;
return *this;
}
 
M

Martijn Lievaart

Because std::endl is a function, not a const char*. Just add this:

message& operator<< (ostream& (*f)(ostream&)){
m_s << f;
return *this;
}

Even better, add:

template<typename t>
message& operator<< (const T& t){
m_s << f;
return *this;
}

as the only operator<< and suddenly everything that can be written to an
ostream can me written to a message.

HTH,
M4
 
A

Andrey Tarasevich

Martijn said:
Even better, add:

template<typename t>
message& operator<< (const T& t){
m_s << f;
return *this;
}

as the only operator<< and suddenly everything that can be written to an
ostream can me written to a message.
...

Not true. (And what Jacques said is not exactly correct either.)
'std::endl' is not a function, it is a function template. The compiler
won't be able to perform template argument deduction if you try to
output 'std::endl' with the above template 'operator<<'.

Jacques' solution will work because it provides compiler with enough
information to perform successful template argument deduction for
'std::endl'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top