Overloading operator <<

B

bart.kowalski

Hello,

I'm trying to overload operator << for class CString, which has an
operator const char *. I thought the following code would do:

template <typename T>
inline std::basic_ostream<T> operator<<(
const std::basic_ostream<T>& p_Stream,
const CString& p_String)
{
p_Stream << static_cast<const T*>(p_String) << std::flush;
return p_Stream;
}

But instead the operator calls itself recursively ad-infinitum. Can
someone explain why?


Bart.
 
H

Heinz Ozwirk

Hello,

I'm trying to overload operator << for class CString, which has an
operator const char *. I thought the following code would do:

template <typename T>
inline std::basic_ostream<T> operator<<(
const std::basic_ostream<T>& p_Stream,
const CString& p_String)
{
p_Stream << static_cast<const T*>(p_String) << std::flush;
return p_Stream;
}

But instead the operator calls itself recursively ad-infinitum. Can
someone explain why?

I'm surprised that it calls anything at all. It shouldn't even compile:

1. p_Stream is a reference to a constant basic_ostream, but operator<<(char
const*) is not a const member.
2. Your operator<< returns a copy of p_Stream, but basic_ostreams are not
copy constructable.

Which compiler are you using?

Heinz
 
B

bart.kowalski

I'm surprised that it calls anything at all. It shouldn't even compile:
Oops. That was obviously my mistake, but VC++ 6.0 didn't complain one
bit. It happily called CString's implicit constructor and then operator
<< again.

Thanks.
 
B

bart.kowalski

Do you need to add &
Yes. I need to pass a non const reference and return this reference. It
was a mistake on my part, but the compiler accepted it even though
there's no copy ctor for basic_ostream.
 

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,774
Messages
2,569,598
Members
45,158
Latest member
Vinay_Kumar Nevatia
Top