考虑以下示例:
template <typename T>
class C
{
public:
friend void f() {}
friend void f(C<T>) {}
};
C<int> c;
void g(C<int>* p)
{
f();
f(*p);
}
使用 GCC 5.2 编译会引发以下编译错误:
no matching function for call to 'f()'
但是标准在 14.6.5 中说:
Friend classes or functions can be declared within a class template. When a template is instantiated, the names of its friends are treated as if the specialization had been explicitly declared at its point of instantiation.
为什么编译失败?在 GCC 3.4 中,它通过了。
最佳答案
f
只能通过参数相关名称查找 (ADL) 找到。第二个调用编译是因为 p
的指针对象作为参数传递的 的类型为 C<int>
- 这会导致 ADL 介入并检查其他不可见的功能。事实上,第一次重载f
根本找不到,因为无法将关联传达给 C
的任何特化.
只需查看您后面的报价,[temp.inject]/2 :
As with non-template classes, the names of namespace-scope friend functions of a class template specialization are not visible during an ordinary lookup unless explicitly declared at namespace scope (11.3). Such names may be found under the rules for associated classes (3.4.2). 141
141) Friend declarations do not introduce new names into any scope, either when the template is declared or when it is instantiated.
关于c++ - 类模板中可见的友元函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32624557/