c++ - 在 C++ 中模板化友元

标签 c++ templates friend

是否可以将友元类做成模板,比如:

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/

相关文章:

c++ - C++中Java静态方法的等价物

c++ - std::is_same - 从 integral_constant 继承函数的用例

java - 与类共享字段方法

C++ getline() 不需要命名空间声明

c++ - 为什么在调用成员函数时 std::reference_wrapper 不隐式转换为引用?

python - 使用 boost.python,如何扩展类的 __dir__ 函数?

html - 检查是否在 Jinja2 模板中未选中复选框

无需滚动的html模板

c++ - 我应该如何正确重载使用 friend 的运算符?

c++ - `template <class> friend class Foo` 是什么意思?