访问友元类私有成员的友元函数

跟随2019 年特拉维夫欧洲电视网的捷克歌曲

众所周知,在 C++ 中,朋友的朋友不是(自动地)朋友。

然而,Clang 在 GCC 和 MSVC 的以下代码上有所不同:

class A {
public:    
    // forward declaration
    class Inner2;

private:
    class Inner1 {
        char foo;
        friend class Inner2;
    };
public:
    class Inner2 {
        Inner1 i;
    public:
        bool operator==(Inner2 other) {
            return i.foo == other.i.foo; // OK by GCC, Clang and MSVC++
        }
        friend bool operator!=(Inner2 a, Inner2 b) {
            return a.i.foo != b.i.foo; // Clang accepts, GCC and MSVC++ reject
        }
    };
};

代码:https : //godbolt.org/z/rn48PTe1Y

哪一个是正确的?如果 Clang 过于宽容是错误的,那么允许访问的最佳方式是什么(除了提供公共 getter?)


注意:如果朋友函数只是在类中声明并在外部实现,Clang 和 GCC 都会拒绝代码。

回答

这似乎是clang 中的一个已知缺陷,错误 id #11515,已在 2011 年报告,但显然仍未修复。

一个更简单的编译示例,但不应该(来自上面的错误报告):

class A {
  int n;
  friend struct B;
};

struct B {
  friend int get(A &a) {
    return a.n; // clang accepts, and should reject
  }
};

https://godbolt.org/z/r78Pazoqj


以上是访问友元类私有成员的友元函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>