【发布时间】:2012-03-26 00:44:52
【问题描述】:
我有两个模板类,templateClass1 和 templateClass2。我想在 templateClass2 中使用 templateClass1 的私有变量和方法。是否可以通过在 c++ 中使用friend关键字来做到这一点?
提交
【问题讨论】:
-
你试过了吗?然后发生了什么?
我有两个模板类,templateClass1 和 templateClass2。我想在 templateClass2 中使用 templateClass1 的私有变量和方法。是否可以通过在 c++ 中使用friend关键字来做到这一点?
提交
【问题讨论】:
我知道这篇文章可能已经死了,但是对于偶然发现这篇文章的其他人......
templateClass1.h
template <class T> class templateClass2; // forward declare
template <typename T>
class templateClass1 {
friend templateClass2<T>;
};
templateClass2.h
template <class T> class templateClass1; // forward declare
template <typename T>
class templateClass2 {
friend templateClass1;
}
【讨论】:
<T>
可以有任何类型的朋友,但是在提供模板参数之前,模板不是类型。因此,一般而言,您必须对您希望与之成为朋友的每种完整类型进行专业化。这将推动您尝试将要成为朋友的类型作为模板参数传递,但您不能提供将成为朋友的模板类型。
例如。这是违法的
template <class T>
class A
{
friend class T;
};
有了这些规定,就很难用模板和友好性来做任何有意义的事情。
【讨论】:
friend T;,因为编译器已经被告知T是一个类型。
friend class identity<T>::type; 而不是 friend T;