Overloaded operator in a Class template

S

Surya Kiran

Hi all,
I've a class template, of which i've an overloaded operator (operator
<<) which was written like this

=============== classa.hpp ===========
template <class T>
class A
{
....
....
friend ostream& operator<< (ostream&, const A<T>&)
}
======================================
and the implementation like this
==== classa.cpp =====
template <class T>
ostream& operator<< (ostream& os, const A<T>& t)
{
....
....
}
======================
When i compile this one, i'm getting errors
saying undefined reference to ostream& operator<< <int> instance (i've
created <int> instance of class A.). What is the correct way to
declare and define an overloaded operator like << to a class template.

One thing i've observed is when i give the definition of the
overloaded operator in the header file itself, its working fine. what
could have been the problem.

Thanks in advance,
Surya
 
D

David Harmon

On 13 Apr 2004 21:25:21 -0700 in comp.lang.c++, (e-mail address removed) (Surya
Kiran) wrote,
One thing i've observed is when i give the definition of the
overloaded operator in the header file itself, its working fine. what
could have been the problem.

In the majority of cases, you must put the entire template code in the
header.

This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[34.12] Why can't I separate the definition of my templates class from
it's declaration and put it inside a .cpp file?". It is always good to
check the FAQ before posting. You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/
 

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

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top