且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在类内部定义的朋友函数的完全限定名称是什么?

更新时间:2023-02-08 19:50:03

依赖于参数的查找是唯一找到val()的方法吗?

Is argument-dependent lookup the only way val() can be found?

是的,这是唯一的方法.要引用 [namespace.memdef]/3 上的圣洁标准:

Yes, it is the only way. To quote the holy standard at [namespace.memdef]/3:

如果非本地类中的朋友声明首先声明了一个类, 朋友是成员的函数,类模板或函数模板 最内层的封闭命名空间.朋友声明不 本身就可以使该名称对不合格的查询或合格的查询可见.

If a friend declaration in a non-local class first declares a class, function, class template or function template the friend is a member of the innermost enclosing namespace. The friend declaration does not by itself make the name visible to unqualified lookup or qualified lookup.

因此,尽管valfoo的成员,但仅从友人声明中查找是不可见的.要使其可见,需要一个类外定义(也是一个声明).对于内联定义(并且没有类外声明),这意味着ADL是调用该函数的唯一方法.

So while val is a member of foo, it's not visible to lookup from the friend declaration alone. An out of class definition (which is also a declaration) is required to make it visible. For an inline definition (and no out-of-class declaration) it means ADL is the only way to call the function.

作为一个额外的奖励,C ++曾经有一个朋友名字注入"的概念.但是,该内容已被删除,并且将ADL的规则进行了替换.可以在WG21论文 N0777中找到更详细的概述. (pdf).

As an added bonus, C++ did once have a concept of "friend name injection". That however has been removed, and the rules for ADL adjusted as a replacement. A more detailed overview can be found in WG21 paper N0777 (pdf).