合格的朋友功能模板实例化 [英] Qualified friend function template instantiation
问题描述
查看 C ++模板:完整指南(第二版) ) / 官方网站今天早上,我遇到了一个部分,我不太明白(12.5.2,如果您有书)。忽略此处无关紧要的内容:
Looking at C++ Templates: The Complete Guide (2nd Edition)/official site this morning I came across a section I can't quite make sense out of (12.5.2 if you have the book). Omitting what seems irrelevant here:
如果[朋友声明中]的名称后没有尖括号,则有两种可能性
If the name [in the friend declaration] is not followed by angle brackets there are two possibilities
-
如果名称不合格[...]
If the name isn't qualified [...]
如果名称是合格的(它包含 ::
),则该名称必须引用先前声明的函数或函数模板。匹配功能优于匹配功能模板。但是,这样的朋友声明不能是定义。
If the name is qualified (it contains ::
), the name must refer to a previously declared function or function template. A matching function is preferred over a matching function template. However, such a friend declaration cannot be a definition.
使用以下代码
void multiply(void*);
template <typename T>
void multiply(T);
class Comrades {
// ... skipping some friends that do not effect the error message
friend void ::multiply(int); // refers to an instance of the template
// ...
};
gcc错误:
error: ‘void multiply(int)’ should have been declared inside ‘::’
friend void ::multiply(int);
^
c语错误:
error: out-of-line declaration of 'multiply' does not match any
declaration in the global namespace
friend void ::multiply(int);
^~~~~~~~
我正试图探底为此,我已经重新键入了几次代码(不过如果有人拿着这本书,也可以再次输入)。规则正确,编译器错误吗?该代码不是该规则的正确证明吗?
I'm trying to get to the bottom of this, and I've retyped the code a few times (though again if someone has the book...). Is the rule right and the compilers are wrong? Is the code not the right demonstration of the rule?
完整的代码包括一个较早的朋友函数定义:
The complete code includes an earlier friend function definition:
class Comrades {
friend void multiply(int) { }
friend void ::multiply(int);
}
使用clang接受和gcc拒绝(这是其他问题)。无论哪种情况,它都没有证明作者陈述的规则,这是第二个引用同一类中较早版本的规则。
Which clang accepts and gcc rejects (that's a different question). In either case it doesn't demonstrate the rule that the author states, it's the second one referencing the earlier one in the same class.
推荐答案
这本书是对的。 [temp.friend] p1 -突出显示相关部分:
The book is right. [temp.friend]p1 - with the relevant part highlighted:
对于不是模板声明的朋友函数声明:
For a friend function declaration that is not a template declaration:
-
if朋友的名字是合格的或不合格的 template-id ,[...]
朋友的名字是 qualified-id ,并且在指定的类或命名空间中找到匹配的非模板函数[...]
if the name of the friend is a qualified-id and a matching non-template function is found in the specified class or namespace, [...]
如果朋友的名字是 qualified-id ,并且在指定的类或命名空间中找到了匹配的函数模板,则朋友声明将引用推导该功能模板的专业化
if the name of the friend is a qualified-id and a matching function template is found in the specified class or namespace, the friend declaration refers to the deduced specialization of that function template
[...]
这篇关于合格的朋友功能模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!