This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: c++ template class problem


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]