c++ template class problem

Nathan Myers ncm@cygnus.com
Thu Sep 24 19:20:00 GMT 1998


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



More information about the Gcc mailing list