c++ - 类模板中可见的友元函数名称

标签 c++ templates language-lawyer friend friend-function

考虑以下示例:

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/

相关文章:

c++ - 对于派生类对象的基类部分,如何在基类中实现运算符重载?

c++ - 解密使用 htpasswd 创建的密码

c++ - 编译时 C++ 项目抛出错误 C2228,这不是预期的,因为控件在运行时未到达该点

c - 按位运算可以移植吗?

c++ - 明确提及预期的分号

c++ - 创建 istringstream 时出现 EXC_BAD_ACCESS

c++ - 如何正确使用通过转发引用传递的可调用对象?

c++ - 将 std::initializer_list 与 bool 重载函数一起使用时重载决议的意外行为

reactjs - WebStorm 功能片段 React

c++ - 模板类的成员函数,将模板类型作为参数