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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With