470,819 Members | 1,640 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,819 developers. It's quick & easy.

template class objects as parameters

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;}


please help!!
Nov 9 '06 #1
1 1470
Obviously, you can. but you need to let the compiler know that they are templates.




C++ Syntax

#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 ;

}
Nov 19 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Istvan Buki | last post: by
3 posts views Thread by Thomas Matthews | last post: by
2 posts views Thread by Siegfried Weiss | last post: by
2 posts views Thread by Nike | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.