What is the difference between "friend struct A;" and "friend A"; syntax?

What is the difference between execution:

struct A; struct B { friend struct A; }; 

and

 struct A; struct B { friend A; }; 

What does it mean to leave a struct in the second part?

+7
c ++ c ++ 11 friend
source share
1 answer

The difference is that if you write friend A; , A must be a known type name, that is, it must be declared earlier.

If you write friend struct A; , this is itself an A declaration, so a preliminary declaration is not required:

 struct B { friend struct A; }; // OK 

However, there are several subtleties. For example, friend class/struct A declares class A in the innermost namespace of class B (thanks to Captain Obvlious ):

 class A; namespace N { class B { friend A; // ::A is a friend friend class A; // Declares class N::A despite prior declaration of ::A, // so ::A is not a friend if previous line is commented }; } 

There are also several other cases where you can only write friend A :

  • A is the name of typedef:

     class A; typedef A A_Alias; struct B { // friend class A_Alias; - ill-formed friend A_Alias; }; 
  • A is a template parameter:

     template<typename A> struct B { // friend class A; - ill-formed friend A; }; 
+13
source share

All Articles