是否可以将友元类做成模板,比如:
template <class T>
class MyClass {
public:
friend class T;
};
我努力得到这个的原因是我正在使用 policy-based design我希望我的策略类能够访问主机成员。 (...现在我开始认为这可能意味着我的设计很糟糕...)
提前谢谢大家!
最佳答案
在 C++03 中,您不允许对模板的参数声明友元。
§7.1.5.3/2
[...] If the identifier resolves to a typedef- name or a template type-parameter, the elaborated-type-specifier is ill-formed. [Note: this implies that, within a class template with a template type-parameter T, the declaration
friend class T;
格式错误。 ]
C++11在这方面有一些变化,但是有点奇怪。 friend class T;
仍然是错误的,但是 friend T
是允许的。引用可以在同一段落中找到:
§7.1.5.3/2
[...] [ Note: This implies that, within a class template with a template type-parameter T, the declaration
friend class T;
is ill-formed. However, the similar declaration friend T; is allowed (11.3). — end note ]
注释不是规范性的,但它们表明了围绕它的规范的意图。我无法找到使注释正确的具体句子,但我认为至少意图是应该允许这样做。
关于c++ - 在 C++ 中模板化友元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9785912/