Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++?

like image 503
xmllmx Avatar asked Dec 11 '22 05:12

xmllmx


1 Answers

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.

like image 132
songyuanyao Avatar answered Jan 05 '23 17:01

songyuanyao