【转】类模板中的友元声明 - 声明依赖性
当授予对给定模板的实例的访问权时候,在作用域中不需要存在该类模板或函数模板的声明。实质上,编译器将友元声明也当作类或函数的声明对待(When we grant access to all instances of a given template, there need not be a declaration for that class or function template in scope. Essentially, the compiler treats the friend declaration as a declaration of the class or function as well.)。
想要限制对特定实例化的友元关系时,必须在可以用于友元声明之前声明类或函数(When we want to restrict friendship to a specific instantiation, then the class or function must have been declared before it can be used in a friend declaration:):想要将友元关系限定在特定的实例化上,则相关的类或函数必须在其友元声明之前进行声明。
template <class T> class A; //在友元声明之前进行声明 template <class T> class B { public: friend class A<T>; // ok: A is known to be a template 告诉编译器A是个友元模板类 friend class C; // ok: C must be an ordinary, nontemplate class 没有声明,编译器当C是个普通非模板类 template <class S> friend class D; // ok: D is a template 当场声明, friend class E<T>; // error: E wasn't declared as a template 模板类的特定实例化的友元声明之前要事先进行模板类声明 friend class F<int>; // error: F wasn't declared as a template 模板类的特定实例化的友元声明之前要事先进行模板类声明 };
如果没有事先告诉编译器该友元是一个模板,则编译器将认为该友元是一个普通非模板类或非模板函数(If we have not previously told the compiler that the friend is a template, then the compiler will infer that the friend is an ordinary nontemplate class or function.)。
转自:http://blog.csdn.net/lychee007/article/details/4432392