c – 与extern“C”函数的友谊似乎要求::限定名称

c – 与extern“C”函数的友谊似乎要求::限定名称,第1张

概述尝试使用一个extern“C”函数做一个类的朋友,这段代码的作用是: #include <iostream>extern "C" { void foo();}namespace { struct bar { // without :: this refuses to compile friend void ::foo(); bar() : v(666) { 尝试使用一个extern“C”函数做一个类的朋友,这段代码的作用是:
#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我必须明确地写::在朋友voID :: foo()中;否则友谊不行.这个::只有当它是extern“C”时才需要.

这是编译器BUG /问题吗?我没想到这个行为.
>如果它不是一个BUG,为什么这是必需的,但只有当它是extern“C”而不是没有它?名称查找规则的更改如何,这使得这是必要的?

我被困了这可能有一些规则,我找不到.

解决方法

[n3290: 7.3.1.2/3]: Every name first declared in a namespace is a
member of that namespace. If a frIEnd declaration in a non-local class
first declares a class or function the frIEnd class or function is a
member of the innermost enclosing namespace. The name of the frIEnd is
not found by unqualifIEd lookup (3.4.1) or by qualifIEd lookup (3.4.3)
95) this implIEs that the name of the class or function is
unqualifIEd. until a matching declaration is provIDed in that
namespace scope (either before or after the class deFinition granting
frIEndship). If a frIEnd function is called,its name may be found by
the name lookup that consIDers functions from namespaces and classes
associated with the types of the function arguments (3.4.2). If the
name in a frIEnd declaration is neither qualifIEd nor a template-ID
and the declaration is a function or an elaborated-type-specifIEr,the
lookup to determine whether the entity has been prevIoUsly declared
shall not consIDer any scopes outsIDe the innermost enclosing
namespace. [..]

最内围的命名空间是匿名的,你没有限定功能名称,所以the name is not found.

命名空间need not be anonymous,也可以.

请注意,问题中的外部“C”是一个红色的鲱鱼,如the following also fails for the same reason:

voID foo();namespace {struct T {   frIEnd voID foo();   private: voID bar() { cout << "!"; }} t;}voID foo() { t.bar(); }int main() {   foo();}/*In function 'voID foo()':line 7: error: 'voID<unnamed>::T::bar()' is privatecompilation terminated due to -Wfatal-errors.*/

[alternative testcase,adapted from your original code]

总结

以上是内存溢出为你收集整理的c – 与extern“C”函数的友谊似乎要求::限定名称全部内容,希望文章能够帮你解决c – 与extern“C”函数的友谊似乎要求::限定名称所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1248216.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存