Re: errors = templates * friends;

From: Rob Williscroft (rtw_at_freenet.co.uk)
Date: 06/25/04


Date: 24 Jun 2004 22:43:26 GMT

John Harrison wrote in news:2k10fiF16m7clU1@uni-berlin.de in
comp.lang.c++:

>>
>> Here's an example of a template friend (note all the cruft):
>>
>> #include <iostream>
>> #include <ostream>
>>
>>
>> /* Forward declare X, so we can forward declare operator <<
>> */
>> template < typename T > struct X;
>> template < typename T >
>> std::ostream & operator << ( std::ostream &os, X< T > const & );
>>
>
> This confuses me, I know what to do but I still don't understand why.
>
> Why is it necessary to forward declare the operator in this case?
>

Because the friend /statement/ in this:

template < typename T >
struct X
{
  friend /* Note the <> */
    std::ostream & operator << <>( std::ostream &os, X< T > const & );
};

isn't a declaration.

The following example contains a declaration but its to generic, i.e. it
grants friendship to widely, not that that is ever a /real/ problem.

#include <iostream>
#include <ostream>

template < typename T >
struct Y
{
  template < typename U >
  friend
    std::ostream &operator << ( std::ostream &os, Y< U > const & );

};

template < typename T >
std::ostream & operator <<( std::ostream &os, Y< T > const & )
{
  os << "friend\n";
  return os;
}

int main()
{
  Y< int > y;
  std::cout << y;
}

Rob.

-- 
http://www.victim-prime.dsl.pipex.com/