> 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 ;
}
Reputation Points: 1159
Solved Threads: 285
Posting Virtuoso
Offline 1,606 posts
since Dec 2006