gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:59:49 24 4
gpt4 key购买 nike

考虑以下示例:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com