简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM