Ryan Haining
Ryan Haining

Reputation: 36832

Declare friend function which is defined in an earlier friend definition

The following defines a friend function in the global namespace, the declares that same function as a friend

class Cls {
    friend void func(int) { }
    friend void ::func(int);
};

clang accepts this, while gcc rejects with

so.cpp:3:17: error: ‘void func(int)’ has not been declared within ‘::’
     friend void ::func(int);
                 ^~
so.cpp:2:17: note: only here as a ‘friend’
     friend void func(int) { }
                 ^~~~

This looks like it should be fine to me, it's defining a function in the global namespace isn't it? The gcc error is pretty explicit about not liking it only being a friend though. Who is right?

Upvotes: 2

Views: 136

Answers (1)

Barry
Barry

Reputation: 303217

From [namespace.memdef]/3:

The friend declaration does not by itself make the name visible to unqualified lookup or qualified lookup.

The declaration:

friend void func(int) { }

does declare the name func in the global namespace. However, that name cannot be found by either unqualified or qualified lookup. It can only be found by ADL (which, since the argument is int, means it cannot be found at all Casey is steely-eyed missile man).

The only way to have ordinary lookup find this func is to additionally provide a declaration for it outside of the class body.

gcc is correct to reject.

Upvotes: 5

Related Questions