Declare friend function which is defined in an earlier friend definition

痞子三分冷 提交于 2020-01-05 04:58:18

问题


The following defines a friend function in the global namespace, the declares that same function as a friend

class Cls {
    friend void func(int) { }
    friend void ::func(int);
};

clang accepts this, while gcc rejects with

so.cpp:3:17: error: ‘void func(int)’ has not been declared within ‘::’
     friend void ::func(int);
                 ^~
so.cpp:2:17: note: only here as a ‘friend’
     friend void func(int) { }
                 ^~~~

This looks like it should be fine to me, its defining a function in the global namespace isn't it? The gcc error is pretty explicit about not liking it only being a friend though. Who is right?


回答1:


From [namespace.memdef]/3:

The friend declaration does not by itself make the name visible to unqualified lookup or qualified lookup.

The declaration:

friend void func(int) { }

does declare the name func in the global namespace. However, that name cannot be found by either unqualified or qualified lookup. It can only be found by ADL (which, since the argument is int, means it cannot be found at all Casey is steely-eyed missile man).

The only way to have ordinary lookup find this func is to additionally provide a declaration for it outside of the class body.

gcc is correct to reject.



来源:https://stackoverflow.com/questions/54055638/declare-friend-function-which-is-defined-in-an-earlier-friend-definition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!