【问题标题】:How to separate a template class from its friend template class into different header files?如何将模板类与其友元模板类分离到不同的头文件中?
【发布时间】:2015-08-05 11:46:56
【问题描述】:

一个文件包含模板类A和模板类B。A是B的朋友。

我想将它们分成不同的文件。如何处理?

【问题讨论】:

  • 您需要更具体。您是否希望每个实例化 A<U> 成为每个 B<T> 的朋友?或者您是否只想让A<T>B<T> 的朋友但A<U> 不是(对于不同的TU)?你看,模板不是任何东西的朋友。模板的实例化是。

标签: c++ class templates friend organization


【解决方案1】:

啊.h

#if !defined(FILE_A_H)
#define      FILE_A_H

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

  // ...
};

#endif

B.h

#if !defined(FILE_B_H)
#define      FILE_B_H

template<class T> class B { /* ... */ };

#endif

注意,如果友元声明中使用的类名还没有声明,就当场前向声明(见http://en.cppreference.com/w/cpp/language/friend)。

更多细节:

【讨论】:

  • 非常感谢!
  • 我已经尝试过你的想法。但它执行失败,编译器报错“B类不能访问A类的私有成员”。
  • @LinXuelei Here 有一个简单的例子(作为朋友,B 可以访问A 的私人成员)。您可以发布您的代码并提供更多详细信息吗?
  • @LinXuelei 你应该编辑你的帖子,添加更多信息,或者提出一个新问题。
  • 感谢您一直以来的回复。
猜你喜欢
  • 2011-09-08
  • 2012-03-14
  • 1970-01-01
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 1970-01-01
相关资源
最近更新 更多