Connecting Tech Pros Worldwide Forums | Help | Site Map

inheriting ostream

enzo
Guest
 
Posts: n/a
#1: Jul 22 '05
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

Jacques Labuschagne
Guest
 
Posts: n/a
#2: Jul 22 '05

re: inheriting ostream


enzo wrote:[color=blue]
>
> l << endl;
>[/color]

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

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

Martijn Lievaart
Guest
 
Posts: n/a
#3: Jul 22 '05

re: inheriting ostream


On Sat, 17 Jan 2004 00:25:27 +1300, Jacques Labuschagne wrote:
[color=blue]
> enzo wrote:[color=green]
>>
>> l << endl;
>>[/color]
>
> Because std::endl is a function, not a const char*. Just add this:
>
> message& operator<< (ostream& (*f)(ostream&)){
> m_s << f;
> return *this;
> }[/color]

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

Andrey Tarasevich
Guest
 
Posts: n/a
#4: Jul 22 '05

re: inheriting ostream


Martijn Lievaart wrote:[color=blue][color=green]
>> enzo wrote:[color=darkred]
>>>
>>> l << endl;
>>>[/color]
>>
>> Because std::endl is a function, not a const char*. Just add this:
>>
>> message& operator<< (ostream& (*f)(ostream&)){
>> m_s << f;
>> return *this;
>> }[/color]
>
> 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.
> ...[/color]

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'.

--
Best regards,
Andrey Tarasevich

Closed Thread