Can friend function of a local class be defined in namespace scope?

129 Views Asked by At

A local class in C++ can have friend functions, but these functions cannot be defined neither inside the class [class.friend] p6:

A function may be defined in a friend declaration of a class if and only if the class is a non-local class and the function name is unqualified.

nor inside the enclosing function [dcl.fct.def.general] p2:

[...] A function shall be defined only in namespace or class scope. [...]

But can friend function of a local class be defined in the global scope as follows:

auto foo() {
    struct A;
    void bar(const A&);
    struct A { 
        friend void bar(const A&);
    };
    bar(A{});
    return A{};
}

using A = decltype(foo());
void bar(const A&) {}

Both Clang and MSVC actually permit it, but GCC prints weird errors:

<source>:5:21: error: 'void bar(const foo()::A&)', declared using local type 'const foo()::A', is used but never defined [-fpermissive]
    5 |         friend void bar(const A&);
      |                     ^~~
<source>:5:21: error: 'void bar(const foo()::A&)' used but never defined
<source>:12:6: warning: 'void bar(const A&)' defined but not used

Online demo: https://godbolt.org/z/Yqoeda94x

Which compiler is correct here?

0

There are 0 best solutions below