【问题标题】:Can one template class can be friend of another template class in c++?一个模板类可以成为 C++ 中另一个模板类的朋友吗?
【发布时间】:2012-03-26 00:44:52
【问题描述】:

我有两个模板类,templateClass1 和 templateClass2。我想在 templateClass2 中使用 templateClass1 的私有变量和方法。是否可以通过在 c++ 中使用friend关键字来做到这一点?

提交

【问题讨论】:

  • 你试过了吗?然后发生了什么?

标签: c++ templates friend


【解决方案1】:

我知道这篇文章可能已经死了,但是对于偶然发现这篇文章的其他人......

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;
}

【讨论】:

  • 您在 templateClass2.h 的第 5 行错过了 &lt;T&gt;
【解决方案2】:

可以有任何类型的朋友,但是在提供模板参数之前,模板不是类型。因此,一般而言,您必须对您希望与之成为朋友的每种完整类型进行专业化。这将推动您尝试将要成为朋友的类型作为模板参数传递,但您不能提供将成为朋友的模板类型。

例如。这是违法的

template <class T> 
class A
{
     friend class T;
};

有了这些规定,就很难用模板和友好性来做任何有意义的事情。

【讨论】:

  • 语法就是friend T;,因为编译器已经被告知T是一个类型。
  • 你可以为基类加好友,但你仍然必须提供访问器,因为友谊不能被继承。
  • 在 C++03 中你必须说 friend class identity&lt;T&gt;::type; 而不是 friend T;
  • stackoverflow.com/questions/702650/… 来自另一个涵盖该主题的 SO 问题
  • 对于 templateClass2 的每个专业化都成为 templateClass2 的朋友还是别的什么?朋友模板Class2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 2014-10-03
  • 2012-03-14
相关资源
最近更新 更多