为什么我不能成为模板参数的朋友?

时间:2022-02-12 01:02:43

When researching an answer to a question (based on this answer) I tried to do the following:

在研究问题的答案时(基于这个答案),我尝试做以下事情:

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

friendly<string> howdy;

This fails to compile with the following error:

无法编译时出现以下错误:

error: template parameter "T" may not be used in an elaborated type specifier friend class T;

错误:模板参数“T”不能用在精心设计的类型说明符朋友类T中;

From what I can understand from my good friend Google this is so that I won't accidentally try to instantiate friendly<int> but why should this be an error when compiling the template? Should't it be an error when instantiating the template with an invalid type (such as had I written int f() { return T::foo(); })

从我的好朋友Google可以理解的是,我不会不小心尝试实例化友好的 ,但为什么在编译模板时这是一个错误?在使用无效类型实例化模板时不应该是错误(例如我写了int f(){return T :: foo();})

2 个解决方案

#1


Section 7.1.5.3 of the standard explicitly describes this as an example of an illformed elaborated type specifier.

该标准的7.1.5.3节明确地将此描述为一个错误的详细类型说明符的示例。

A discussion about the subject can be found here.

关于这个问题的讨论可以在这里找到。

#2


A bit more googleling brought up Extended friend Declarations (PDF) for C++0x.

更多googleling带来了C ++ 0x的扩展好友声明(PDF)。

This document contains the following:

本文档包含以下内容:

template <typename T> class R {
    friend T;
};
R<C> rc; // class C is a friend of R<C>
R<int> ri; // OK: “friend int;” is ignored

Which goes even further than what I thought (ignoring illegal friend decelerations rather than failing during instantiation). So I guess the answer is that there isn't a good reason and it's being rectified.

这比我的想法更进一步(忽略非法的朋友减速而不是在实例化期间失败)。所以我想答案是没有充分的理由而且它正在被纠正。

#1


Section 7.1.5.3 of the standard explicitly describes this as an example of an illformed elaborated type specifier.

该标准的7.1.5.3节明确地将此描述为一个错误的详细类型说明符的示例。

A discussion about the subject can be found here.

关于这个问题的讨论可以在这里找到。

#2


A bit more googleling brought up Extended friend Declarations (PDF) for C++0x.

更多googleling带来了C ++ 0x的扩展好友声明(PDF)。

This document contains the following:

本文档包含以下内容:

template <typename T> class R {
    friend T;
};
R<C> rc; // class C is a friend of R<C>
R<int> ri; // OK: “friend int;” is ignored

Which goes even further than what I thought (ignoring illegal friend decelerations rather than failing during instantiation). So I guess the answer is that there isn't a good reason and it's being rectified.

这比我的想法更进一步(忽略非法的朋友减速而不是在实例化期间失败)。所以我想答案是没有充分的理由而且它正在被纠正。