Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which scope does an in-class-defined friend function belong to?

Tags:

c++

class A {
    friend void f() {}
};

// void f() {}  // compile error: redifinition of 'void f()'

int main() {
    f();  // compile error: 'f' is not declared in this scope
}

As you can see in the above example, if f is called in A's enclosing namespace scope, the compiler just can't find f, which gives me the idea that f is not in this scope. But when an out-of-calss definition of a function with the same signature is added, the compiler issues an error of function redefinition, which gives me the opposite idea that f is actually in this scope.

So, I'm puzzled which scope an in-class-defined friend function belongs to.

like image 990
goodbyeera Avatar asked Oct 21 '22 15:10

goodbyeera


1 Answers

It's in the namespace containing the class.

However, if it's only declared in the class, then it's only available by argument-dependent lookup. So this would work, with the argument type A finding f in the surrounding namespace:

class A {
    friend void f(A) {}
};

int main() {
    f(A());    // OK: uses ADL
    ::f(A());  // Error: doesn't use ADL, and can't find the name without it
}

This is often used for overloaded operators, which can only be found by ADL anyway.

Your version would work if you declared, rather than redefined, the function at namespace scope.

void f();
like image 70
Mike Seymour Avatar answered Nov 15 '22 10:11

Mike Seymour