与外部“C”的友谊函数似乎需要 :: 来限定名称
尝试使用 extern "C"
函数创建一个 class
朋友,这段代码有效:
#include <iostream>
extern "C" {
void foo();
}
namespace {
struct bar {
// without :: this refuses to compile
friend void ::foo();
bar() : v(666) {}
private:
int v;
} inst;
}
int main() {
foo();
}
extern "C" {
void foo() {
std::cout << inst.v << std::endl;
}
}
但我非常惊讶地发现,使用 g++ 4.6.1 和 4.4.4 我必须在 friend void ::foo();
中明确写入 ::
,否则友谊不起作用。这个 ::
仅当它是 extern "C"
时才需要。
- 这是编译器错误/问题吗?我没想到会有这种行为。
- 如果这不是一个错误,为什么需要这样做,但只有当它是
extern "C"
时而不是没有它时?名称查找规则的变化使得这成为必要吗?
我很困惑。可能有一些我找不到的规则。
Trying to make a class
friends with an extern "C"
function, this code works:
#include <iostream>
extern "C" {
void foo();
}
namespace {
struct bar {
// without :: this refuses to compile
friend void ::foo();
bar() : v(666) {}
private:
int v;
} inst;
}
int main() {
foo();
}
extern "C" {
void foo() {
std::cout << inst.v << std::endl;
}
}
But I was very surprised to find that with g++ 4.6.1 and 4.4.4 I have to explicitly write ::
in friend void ::foo();
otherwise the friendship doesn't work. This ::
is only needed when it's extern "C"
though.
- Is this a compiler bug/problem? I wasn't expecting that behaviour.
- If it isn't a bug why is this required, but only when it's
extern "C"
and not without it? What about the name lookup rules changes that makes this necessary?
I'm stumped. There is probably some rule for this that I can't find.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最内层的封闭命名空间是匿名命名空间,并且您没有限定函数名称,因此 该名称不是发现。
命名空间也不必是匿名的。
请注意,问题中的
extern“C”
是一个转移注意力的问题,因为以下内容也因同样的原因而失败:[替代测试用例,改编自您的原始代码]
The innermost enclosing namespace is the anonymous one, and you didn't qualify the function name, so the name is not found.
The namespace need not be anonymous, either.
Note that the
extern "C"
in the question is a red herring, as the following also fails for the same reason:[alternative testcase, adapted from your original code]