Connecting Tech Pros Worldwide Forums | Help | Site Map

Overloaded operator in a Class template

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

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

re: Overloaded operator in a Class template


Surya Kiran wrote:

[...]
[color=blue]
> 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.[/color]

Yes, that'll do it.

http://www.parashift.com/c++-faq-lit...html#faq-34.12

--
Regards,
Buster.
David Harmon
Guest
 
Posts: n/a
#3: Jul 22 '05

re: Overloaded operator in a Class template


On 13 Apr 2004 21:25:21 -0700 in comp.lang.c++, skg@fluent.co.in (Surya
Kiran) wrote,[color=blue]
>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.[/color]

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/

Closed Thread