Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ inline definition of friend function

In the current draft of the C++ standard (march 2019) [class.friend] p.6 states (emphasis mine):

A function can be defined in a friend declaration of a class if and only if the class is a non-local class ([class.local]), the function name is unqualified, and the function has namespace scope. [...]

What does "the function has namespace scope" mean?

The only situation that I could come up with in which the function does not have namespace scope is the following:

struct A
{
    static void f();

    struct B
    {
        friend void f() {}; 
    }; 
};

However both clang and gcc do not associate the friend definition inside B to the static method inside A, but to a function that belongs to the global namespace.

Are there other situations I am missing?

like image 614
user42768 Avatar asked Mar 22 '19 21:03

user42768


Video Answer


1 Answers

I think that you have actually answered your own question, but without realizing it.

"The function has namespace scope" means that it is part of a namespace, not part of a class or struct. So the function A::B::f() doesn't exist. And it doesn't refer to A::f() either. Instead, the function you have defined as the friend is actually the function ::f(), since that is the namespace that it resides in (the global namespace).

I suspect (but have not tried), that if you wrap all of this in a namespace, then the f() you are defining would be a part of that namespace. So, for example,

namespace ns {
    struct A
    {
        static void f();

        struct B
        {
            friend void f() {}; 
        }; 
    };
}

would define the friend function as the function ns::f().

like image 69
Steven W. Klassen Avatar answered Sep 28 '22 07:09

Steven W. Klassen