gpt4 book ai didi

c++ - 模板特化的友元声明失败

转载 作者:可可西里 更新时间:2023-11-01 17:52:24 31 4
gpt4 key购买 nike

以下包含友元声明的代码因指示错误而失败(请参阅 http://ideone.com/Kq5dy):

template<class T> void foo() {}

template<typename T>
class A {
void foo();
friend void foo<T>(); // error: variable or field 'foo' declared void
};

int main()
{
foo<int>();
}

如果友元声明和成员函数声明的顺序颠倒,则代码编译没有问题(参见 http://ideone.com/y3hiK ):

template<class T> void foo() {}

template<typename T>
class A {
friend void foo<T>();
void foo();
};

int main()
{
foo<int>();
}

如果友元声明不包含模板特化,则不会发生这种情况:非模板友元和模板友元都可以。在模板特化中使用限定名也允许代码编译。我的问题是为什么第一个例子失败了?似乎编译器在 friend 声明时在​​类范围内查找名称并且仅用于模板特化?在标准中的何处指定了此行为?

最佳答案

为了明确表示它是您想要成为的函数 -friend 在函数名称前加上 :: 以表明它在全局命名空间中。

可编译并执行您想要的操作的代码段:

template<class T> void foo() {}

template<typename T>
class A {
void foo();
friend void ::foo<T>();
};

int main()
{
foo<int>();
}

n1905.pdf

3.4/9 Name Lookup

Name lookup for a name used in the definition of a friend function (11.4) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions. If the friend function is not defined in the class granting friendship, name lookup in the friend function definition shall proceed as described for lookup in namespace member function definitions

您的代码段无法编译,原因与以下代码无法编译的原因相同。

template<class T> void foo () {}

template<typename T>
struct A {

void foo ();

void func () {
foo<T> (); // when performing the name lookup A::foo is
// found before ::foo<T>
}
};

...

14.5.3 Friends [temp.friend] 1

A friend of a class or class template can be a function template or class template, a specialization of a function template or class template, or an ordinary (non-template) function or class. For a friend function declaration that is not a template declaration:

— if the name of the friend is a qualified or unqualified template-id, the friend declaration refers to a specialization of a function template, otherwise

— if the name of the friend is a qualified-id and a matching non-template function is found in the specified class or namespace, the friend declaration refers to that function, otherwise,

— if the name of the friend is a qualified-id and a matching specialization of a function template is found in the specified class or namespace, the friend declaration refers to that function template specialization, otherwise,

— the name shall be an unqualified-id that declares (or redeclares) an ordinary (non-template) function.

关于c++ - 模板特化的友元声明失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8514880/

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