Following the Czech song from Eurovision 2019 in Tel-Aviv
It is known that in C++ a friend of a friend is not (automatically) a friend.
Clang however differs on the following code with GCC and 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
}
};
};
Code: https://godbolt.org/z/rn48PTe1Y
Which one is correct? If Clang is wrong by being too permissive, what is the best way to allow access (other than providing a public getter?)
A note: if the friend function is just declared in the class and implemented outside, both Clang and GCC reject the code.
operator!=()
- which is not a friend ofInner1
to access private members ofInner1
. A way to correctly provide access (which doesn't rely on all compilers having a bug like clang does) would be to make theoperator!=()
a member ofInner2
rather than afriend
- sinceInner2
is afriend
already, its members will correctly have access to members of instances ofInner1
. – Pola