Search code examples
c++syntaxgrammarfriend

Trying to understand the "template <class U> friend class B;" syntax


The following is a simple c++ program that compiles with my MinGW compiler, and executes as expected:

#include <iostream>


template <class T> class A {
    T a;
    template <class U> friend class B;

  public:
    A<T> (T t) : a(t) {}
};



template <class T> class B {
   A<T> aa;

  public:

    B<T> (T t) : aa(t) {}

    T getT() const {return aa.a;}
};


int main() {
    B<int> b(5);
    std::cout << "> " << b.getT() << std::endl;
}

Since B<T>::getT() accesses the private A<T>::a member, A<T> makes B<T> a friend with template <class U> friend class B; line.

Unfortunately, I don't know why this line needs to be written like this. Intuitively, I would have expected something like friend class B<T>, yet, this doesn't compile.

The meaning of the newly introduced U is unclear as well, since A's and B's dependant type is T in both cases.

So, in short, I'd appreciate any light on how the syntax for this line is derived or deduced.


Solution

  • There are many different permutations of friendship and templates.

    Your present code makes any template specialization of B into a friend for A<T>, so for example B<char> is a friend of A<int>.

    If you only wanted to make the matching A<T> a friend, you would say it like this:

    template <typename> class B;  // forward declare above!
    
    template <typename T>
    class A
    {
        // ...
    
        friend class B<T>;
    };