隐藏的朋友:声明和定义

Evg*_*Evg 12 c++ friend argument-dependent-lookup

安东尼·威廉姆斯在他最近的博客文章中谈到了隐藏的朋友。如果我理解正确的话,主要思想是在某些情况下 ADL 无法找到声明为友元的函数。简单的例子:

namespace N {
    struct A {
        friend void foo(A) { }
    };

    struct B {
        operator A();
    };

    // (*)
    void bar(A) { }
}

void func() {
    N::A a;
    bar(a);   // OK, bar is found via ADL
    foo(a);   // OK, foo is found via ADL

    N::B b;
    bar(b);   // OK, bar is found via ADL
    foo(b);   // NOT OK, foo cannot be found
}
Run Code Online (Sandbox Code Playgroud)

在博客文章的所有示例中,友元函数都是在类内定义的。是否可以声明一个友元函数,然后在该点定义它(*),以便它保持隐藏状态?看起来隐藏的朋友只能在类范围(或另一个编译单元)中定义。

Xar*_*arn 11

隐藏的朋友可以被不合时宜地定义,但他们不会隐藏在那个 TU 中。作为示例,请考虑以下标头:

class A {
    // this is hidden friend defined inline
    friend int operator+(A, int) { return 0; }
    // this is hidden friend defined out of line
    friend int operator+(int, A);
    // not a hidden friend (see below)
    friend int operator+(A, A);
};
int operator+(A, A); // this is no longer hidden friend in any TU
Run Code Online (Sandbox Code Playgroud)

然后是一个单独的 cpp 文件:

#include "a.hpp"

// This is not a hidden friend in this TU, but is in other TUs.
int A::operator+(int, A) {
    return 2;
}
Run Code Online (Sandbox Code Playgroud)

当您的操作符/ADL 自定义点依赖于其他大型标头来实现时,这样做非常有用。


Bok*_*oki 8

隐藏的朋友需要完全内联定义,即在类的定义内部。是的,如果您在其他地方定义友元,其中定义可能会导致名称空间可见性,那么它将打破基于隐藏友元的限制,仅通过 ADL 搜索找到匹配项,因此成为重载解析的候选者。

此外,在WG21关于指定隐藏好友的建议中,我们注意到隐藏好友是完全内联定义的,如以下代码片段所示:

#include <ostream>
#include <compare>
class C  {
    friend ostream& operator << ( ostream&, C const& )  {}
    friend auto   operator <=>( C const&, C const& )  = default;
};
Run Code Online (Sandbox Code Playgroud)