c++ - 模板友元声明中的作用域和前置声明问题
迷茫
迷茫 2017-04-17 13:07:40
0
1
634
// 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的前置声明?
};
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
大家讲道理

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 the Pal3 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 inside class C of Pal<C> and template<typename T> class Pal2.

PS: To be honest, template<typename T> friend class Namethis kind is rarely used, I just haven’t seen it before, Pal<C>this kind has been used before.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template