can u pass template class objects as parameters to friend functions of the same class??
i tried sumthin like...

template<class T>
class array
{
T a[10];
int n;
public:
friend istream& operator>>(istream&,array&);
friend ostream& operator<<(ostream&,array&);};

istream& operator >>(istream& din,array& b)
{
din>>b.n ; //size of array
for(inti=0;i<b.n;i++)
din>>b.a[i];
return(din);
}

ostream& operator<<(ostream &dout,array &b)
{
for(int i=0;i<b.n;i++)
dout<<b.a[i]<<" ";
}
void main()
{
array<int> iarray;
cin>>iarray;
cout<<iarray;}

> can u pass template class objects as parameters to friend functions of the same class??

obviously, you can. but you need to let the compiler know that they are templates.

#include <iostream>

// declare things first
template< typename T > class array ;

template< typename T >
std::istream& operator>> ( std::istream& din, array<T>& b ) ;

template< typename T >
std::ostream& operator<< ( std::ostream &dout, const array<T> &b) ;

// define them now
template< typename T > class array
{
  T a[10] ;  // concept: T is default_constructible
  int n ;

  // <> tells the compiler that the friend is a template.
  // http://www.parashift.com/c++-faq-lite/templates.html#faq-35.16
  friend std::istream& operator>> <> ( std::istream&, array<T>& ) ;
  friend std::ostream& operator<< <> ( std::ostream&,
                                       const array<T>& ) ;
  //...
};

template< typename T >
std::istream& operator>> ( std::istream& din, array<T>& b )
{
  din >> b.n ; // what happens if the user enters a value > 10 ?
  for( int i=0; i<b.n; ++i ) din >> b.a[i] ;
  return din ;
}

template< typename T >
std::ostream& operator<< ( std::ostream &dout, const array<T> &b)
{
  dout << b.n << '\n' ;
  for( int i=0 ; i<b.n ; i++) dout<<b.a[i] << " " ;
  return dout << '\n' ;
}

int main()
{
  array<int> iarray ;
  std::cin >> iarray ;
  std::cout << iarray ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.