模板特化的友元声明失败
以下包含朋友声明的代码失败并显示错误(请参阅 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>();
}
如果好友声明不包含模板专门化,则不会发生这种情况:非模板好友以及模板好友都可以。此外,在模板专业化中使用限定名称允许代码编译。 我的问题是为什么第一个例子失败了?编译器似乎在友元声明时在类作用域中查找名称,并且仅用于模板专业化?标准中的何处指定了这种行为?
The following code containing friend declaration fails with indicated error (see 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>();
}
If the order of friend declaration and member function declaration reversed, then the code compiles without problems (see http://ideone.com/y3hiK):
template<class T> void foo() {}
template<typename T>
class A {
friend void foo<T>();
void foo();
};
int main()
{
foo<int>();
}
This doesn't happen if the friend declaration doesn't contain template specialization: non-template friends are ok, as well as a template friends. Also using qualified name in template specialization allows code to compile.
My question is why does the first example fail? It seems compiler looking up names in class scope at the point of friend declaration and only for template specialization? Where in the Standard this behavior is specified?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了明确表明您想要成为该函数的
friend
,请在函数名称前添加::
来表示它位于全局命名空间中。编译并执行您想要的操作的片段:
n1905。 pdf
您的代码片段无法编译,原因与以下代码无法编译的原因相同。
...
To make it explicit that it's that function you want to be-
friend
prepend the function name with::
to say that it's in the global namespace.Snippet that compiles and does what you want:
n1905.pdf
Your snippet fails to compile because of the same reason as the code below fails to compile.
...