Search code examples
c++c++11templatesstandardsfriend

Why can't a template type be a friend class in C++?


template<typename T>
class A
{
    friend class T;
    int n;
};

struct B
{
    B()
    {
        A<B>{}.n; 
        // error : 'n' is a private member of 'A<B>'
    }
};

Why can't a template type be a friend class in C++?


Solution

  • With the usage of keyword class, you're forward declaring a new type named T; which doesn't refer to the template parameter T. (It shadows the template parameter T in fact.)

    Just remove the keyword class, then the friend declaration won't forward declare a new type.

    template<typename T>
    class A
    {
        friend T;
        int n;
    };
    

    This usage (friend simple-type-specifier; friend typename-specifier;) was introduced since C++11.