Re: How to define inserter or extractor for a class template
On Oct 8, 8:57 am, laikon <lai...@gmail.com> wrote:
this question is about how to define friend functions for a
class template.
It's difficult:-).
the following is an example.
template <typename T>
class Array
{
private:
T* parr;
int sz;
friend ostream& operator << (ostream& os, const Array<T>& rhs);
Note that this declares a non-template operator<< as a friend.
That's probably not what you want.
};
template <class T>
ostream& operator << (ostream& os, const Array<T>& rhs)
{
for (int i = 0; i < rhs.sz; ++i)
os << rhs.parr[i] << "\t";
return os;
}
these codes work well in VC++ 6.0, while linking errors are
given in VC ++ 2005.
If you have a declaration of the operator<<, as a template,
before you define the class, I think it should work. In
practice, I've found it more convenient to only use inline
friends, so the problem doesn't come up. Something like:
template< typename T >
class Array
{
// ...
public:
void print( std::ostream& dest ) const ;
friend std::ostream&
operator<<( std::ostream& dest,
Array< T > const& array )
{
array.print( dest ) ;
return *this ;
}
} ;
The friend may be a non-template function, but it doesn't
matter, since I don't have to declare it anywhere else.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34