This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: c++ template class problem
- To: egcs at cygnus dot com
- Subject: Re: c++ template class problem
- From: Nathan Myers <ncm at cygnus dot com>
- Date: Thu, 24 Sep 1998 16:29:00 -0700
- Newsgroups: cygnus.egcs
- Organization: http://www.cantrip.org/
- References: <199809231033.TAA06844.cygnus.egcs@rothko.qua.srl.melco.co.jp>
Toshinao ISHII wrote:
> I tried compiling the following C++ source using template.
> g++ (egcs-2.92.07) give the following error...
> --------------------------------------------------------------
> // poi01.CC
>
> #include <iostream.h>
>
> template <class T> class C;
Add a forward declaration:
template <class U>
ostream& operator<<( ostream&, const C<U>& );
>
> template <class T> class C
> {
> public:
> T v;
> C() { v = 0; }
> ~C() {}
> friend ostream& operator << <>( ostream &, const C<T>& );
And the friend:
template <class U>
friend ostream& operator<<( ostream&, const C<U>& );
> };
>
> template <class T>
> ostream& operator << ( ostream &os, const C<T>& c )
> {
> os << c;
> return os;
> }
>
> int main()
> {
> C<double> tcd;
> tcd.v = 3.14;
> cout << tcd << endl;
> }
> --------------------------------------------------------------
The rest is OK. However, it's usually better to provide public
member function and then let the operator<< use the function:
> template <class T> class C
> {
> public:
> T v;
> C() { v = 0; }
> ~C() {}
> void print( ostream& os) { os << c; }
}
> template <class T>
> ostream& operator << ( ostream &os, const C<T>& c )
> { c.print(os); return os; }
Nathan Myers
ncm@cygnus.com