Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

friend

What is the difference between doing:

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

and

struct A;
struct B { friend A; };

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

like image 919
Walter Avatar asked Oct 23 '14 22:10

Walter


1 Answers

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

If you write friend struct A;, this itself is a declaration of A, so no prior declaration is needed:

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

There are several subtleties though. For example, friend class/struct A declares class A in innermost enclosing 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
    };
}

Also there are several other cases when you can write only friend A:

  1. A is a typedef-name:

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

    template<typename A>
    struct B { 
        // friend class A;  - ill-formed
        friend A;
    };
    
like image 136
Anton Savin Avatar answered Oct 23 '22 06:10

Anton Savin