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/


Relevant Pages

  • Re: Circular Class Template Friendship
    ... > My issue is the syntax of declaring a friend class within ... > which the string is a fixed width that is specialized. ... it is still possible to have Name_Id_Table template ... the friend class declaration. ...
    (comp.lang.cpp)
  • Re: Template friendship to nested template class
    ... friend struct INNER; ... Probably you are missing an EXTRA template to declare ... I think it's because the name referred to in a 'friend' declaration is looked up to exist at the namespace scope. ...
    (microsoft.public.vc.language)
  • Re: friend class in template
    ... This template takes 3 type parameters, the first of which is named ... The friend declaration attempts to declare the class ... the friend declaration doesn't do what the author apparently ... thought it would do (at least not on a conforming compiler). ...
    (microsoft.public.vc.language)
  • Re: template inner class friendship
    ... template <typename X> ... friend class inner; ... friend class someclass; ...
    (microsoft.public.vc.language)
  • Re: Class templates and friend function templates
    ... > expected the friend declaration to resolve to: ... > as a friend of C. ... The confusion stems from the expectation that function ... template instantiation is similar to class template ...
    (microsoft.public.vc.language)