Topic: Simple template question


Author: jamshid@ses.com (Jamshid Afshar)
Date: Mon, 18 Jul 1994 19:38:44 GMT
Raw View
In article <30cspb$drf@argo.unm.edu>, Raikanta Sahu <rsahu@unm.edu> wrote:
>I don't understand why g++ does not link the following file. Do I have
>to define the << operator explicitly for int and double type?
>
>#include <iostream.h>
>
>template <class Type> class max {
>   public :
>     friend ostream &operator<<(ostream &, max<Type> &) ;
>} ;
>
>template <class Type>
>ostream &operator<<(ostream &out, max<Type> &) { return out ; }
>
>int main() {
>   max<int> a;
>   max<double> b;
>   cout << a << b << endl ;
>   return 0 ;
>}

I don't know why g++ does not link the program.  I have reported the
bug in the past so maybe the new 2.6 compiles and links your code.

If g++ were complaining at *compile* time, I would say the problem is
that the ARM requires template function arguments to match exactly.
This rule has been relaxed in the ANSI/ISO Working Paper, but older
and even some current compilers do not allow `cout << a' to match:

 template <class Type>
 ostream &operator<<(ostream &out, max<Type> &);

because `cout' is an ostream_with_assign, a derived class of ostream.

Jamshid Afshar
jamshid@ses.com




Author: rsahu@unm.edu (Raikanta Sahu)
Date: 17 Jul 1994 21:26:35 -0600
Raw View
I don't understand why g++ does not link the following file. Do I have
to define the << operator explicitly for int and double type?

Thanks.

-Raikanta

----------------------------------------------------------------------
// File : temptest.c

#include <iostream.h>

template <class Type>
class max {

   Type val ;

   public :

     max(Type a, Type b){ val = a > b ? a : b ; }
     friend ostream &operator<<(ostream &, max<Type> &) ;
} ;

template <class Type>
ostream &operator<<(ostream &out, max<Type> &a)
{
  out << a.val ;
  return out ;
}

int main()
{

max<int> a(45, 67) ;
max<double> b(45.8, 67.8) ;

cout << a << b << endl ;

return 0 ;
}