C++ Logo

std-discussion

Advanced search

Re: Local classes and friend functions

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Fri, 29 Sep 2023 13:09:44 -0500
On Fri, 29 Sept 2023 at 12:48, Vladimir Grigoriev via Std-Discussion <
std-discussion_at_[hidden]> wrote:

> In the C++23 Standard there is written (11.9.4 Friends):
>
> «11 If a friend declaration appears in a local class (11.6) and the name
> specified is an unqualified name, a prior declaration is looked up without
> considering scopes that are outside the innermost enclosing non-class
> scope. For a friend function declaration, if there is no prior declaration,
> the program is ill-formed. For a friend class declaration, if there is no
> prior declaration, the class that is specified belongs to the innermost
> enclosing non-class scope, but if it is subsequently referenced, its name
> is not found by name lookup until a matching declaration is provided in the
> innermost enclosing non-class scope.»
>
> and there is also provided an example (I have simplified it)
>
> void f()
> {
> extern void b();
>
> class A
> {
> friend void b(); // OK
> };
> }
> In this case a question arises: How can the friend function b access an
> object of the local class A? The name A is not visible outside the block
> scope of the function f.
>

It can become visible via a deduced return type.


> If it is possible can anybody provide an example of such a function?
>

auto f() {
    extern int b();
    class A {
        friend int b(); // OK
        int i = 1;
    };
    return A();
}
int b() { return f().i; }

Note that gcc rejects; this is
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101356 .

Received on 2023-09-29 18:09:57