// forward declaration necessary to be friend a specific instantiation of a template
template <typename T> class Pal;
class C {
friend class Pal<C>;
template <typename T> friend class Pal2;
};
template <typename T> class C2
{
friend class Pal<T>;
// a template declaration for Pal must be in scope
//上面这句注释的在作用域内是什么意思?Pal的模板声明明明在class C2的外面
friend class Pal3; //为什么不需要Pal3的前置声明?
};
In your example, the
Pal
class has been declared. The scope does not mean that it can be called scope only when it is written into the C2 class. Scope should be translated into context. The context includes the classes defined in{}
.{}
Classes defined outside.The original intention of the friend is to tell the compiler to break through the access restrictions of C++
private
. It does not involve the linking process, so the compiler only needs to know which class has this permission, and does not care about the implementation of the class. An ordinary class only needs a name, just like thePal3
written in your example, while the template class is a little more special. The template class requires template parameters to be combined to be an actual class, and everything is insideclass C
ofPal<C>
andtemplate<typename T> class Pal2
.PS: To be honest,
template<typename T> friend class Name
this kind is rarely used, I just haven’t seen it before,Pal<C>
this kind has been used before.