Search code examples
c++templateslanguage-lawyerfriend-function

Should a friend function of a class template become friend to all instantiations?


Consider the following snippet:

template<typename T> struct Foo {
    friend void bar(Foo, Foo<char> f) {
        static_cast<void>(f.private_field);  // Should only compile when friends with Foo<char>.
    }
private:
    int private_field{};
};

int main() {
    bar(Foo<char>{}, Foo<char>{});  // Compiles.
    bar(Foo<bool>{}, Foo<char>{});  // Compiles erroneously?
}

It compiles successfully with trunk (as of May 6, 2020) GCC, but not with Clang and MSVC: see Godbolt.

Who is right here?

Error messages from Clang and MSVC are as expected:

<source>:3:29: error: 'private_field' is a private member of 'Foo<char>'

        static_cast<void>(f.private_field);  // Should only compile when friends with Foo<char>.

                            ^

<source>:11:5: note: in instantiation of member function 'bar' requested here

    bar(Foo<bool>{}, Foo<char>{});  // Compiles erroneously?

    ^

<source>:6:9: note: declared private here

    int private_field{};

        ^

1 error generated.

Compiler returned: 1

and

example.cpp

<source>(3): error C2248: 'Foo<char>::private_field': cannot access private member declared in class 'Foo<char>'

<source>(6): note: see declaration of 'Foo<char>::private_field'

<source>(2): note: see declaration of 'Foo<char>'

<source>(2): note: while compiling class template member function 'void bar(Foo<bool>,Foo<char>)'

<source>(11): note: see reference to function template instantiation 'void bar(Foo<bool>,Foo<char>)' being compiled

<source>(11): note: see reference to class template instantiation 'Foo<bool>' being compiled

Compiler returned: 2

Solution

  • GCC is plainly wrong here: because each specialization defines its own separate friend function (as it must to avoid duplicate definition errors), bar(Foo<char>,Foo<char>) is a friend of Foo<char> but bar(Foo<char>,Foo<char>) is not. The standard contains a relevant example that mentions a very similar case.