Overloaded operator in a Class template



 DEVELOP > c-Plus-Plus > Overloaded operator in a Class template

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "Surya Kiran"
Date: 13 Apr 2004 11:25:21 PM
Object: Overloaded operator in a Class template
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
.

User: "David Harmon"

Title: Re: Overloaded operator in a Class template 14 Apr 2004 12:13:29 AM
On 13 Apr 2004 21:25:21 -0700 in comp.lang.c++,
(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/
.

User: "Buster"

Title: Re: Overloaded operator in a Class template 14 Apr 2004 12:07:24 AM
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.

Yes, that'll do it.
http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.12
--
Regards,
Buster.
.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER