声明在较早的朋友定义中定义的朋友功能 [英] Declare friend function which is defined in an earlier friend definition

查看:122
本文介绍了声明在较早的朋友定义中定义的朋友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下在全局名称空间中定义了一个朋友函数,声明了与朋友相同的函数

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接受,而 gcc拒绝

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) { }
                 ^~~~

这对我来说应该没问题,它是在全局名称空间中定义一个函数,不是吗? gcc错误非常明确地表明它不喜欢它,只是成为朋友。谁是对的?

This looks like it should be fine to me, it's 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?

推荐答案

来自 [namespace.memdef] / 3


The朋友声明本身不会使名称对不合格的查找或合格的查找可见。

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

声明:

friend void func(int) { }

确实在全局命名空间中声明名称 func 。但是,不能通过非限定或限定查找来找到该名称。它只能由ADL找到(,由于参数为 int ,这意味着根本找不到它 凯西眼花steel乱导弹人)。

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).

进行普通查找的唯一方法是找到此 func 的唯一方法是在类外为其提供声明身体。

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

gcc是正确的拒绝对象。

gcc is correct to reject.

这篇关于声明在较早的朋友定义中定义的朋友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆