Friends of Templates

T

Tom McCallum

Hi,

Can someone please tell me the correct syntax (if its possible of course)
to specify an output stream operator for a templated class so that I dont
need to write the same function for all the derived classes from the
template. I have a sample of what it thought it might look like below.


==BEGIN CODE SNIPPET===

template<class T1, class T2>
class MyDerived : public MyClass {
friend ostream& operator<< (ostream& os, MyDerived<T1, T2> * sa);
....
};

template<class T1, class T2>
ostream& operator<< (ostream& os, MyDerived<T1, T2> * sa) {
}

===END CODE SNIPPED====

Thanks in advance for any suggestions.

Cheers

Tom
 
D

David Hilsee

Tom McCallum said:
Hi,

Can someone please tell me the correct syntax (if its possible of course)
to specify an output stream operator for a templated class so that I dont
need to write the same function for all the derived classes from the
template. I have a sample of what it thought it might look like below.


==BEGIN CODE SNIPPET===

template<class T1, class T2>
class MyDerived : public MyClass {
friend ostream& operator<< (ostream& os, MyDerived<T1, T2> * sa);
...
};

template<class T1, class T2>
ostream& operator<< (ostream& os, MyDerived<T1, T2> * sa) {
}

===END CODE SNIPPED====

Thanks in advance for any suggestions.

Not sure why the above code takes a pointer instead of the usual const
reference.

This is covered in the FAQ (http://www.parashift.com/c++-faq-lite/). See
section 34 ("Container classes and templates"), question 15 ("Why do I get
linker errors when I use template friends?").
 

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
474,174
Messages
2,570,940
Members
47,485
Latest member
Andrewayne909

Latest Threads

Top