Argument dependent search for friends function

Consider the following:

namespace N { struct A { }; struct B { B() { } B(A const&) { } friend void f(B const& ) { } }; } int main() { f(N::B{}); // ok f(N::A{}); // error } 

In the first case, the case succeeds - we consider the associated namespaces N::B and find N::f(B const&) . Fine.

The second case fails. What for? According to [namespace.memdef] :

If a friend declaration in a non-local class first declares a class, function, template, or function template, it is a member of the innermost enclosing namespace. [...] If the template of the function or function of a friend, its name can be found by a name that considers functions from namespaces and classes associated with the types of function arguments (3.4.2).

The associated namespace N::A is N , of which f is a member, so why is it not found by searching?

+7
c ++ language-lawyer argument-dependent-lookup friend-function
source share
1 answer

This is because f not declared in the associated class. B is an associated class when the argument is of type B , but not when the argument is of type A

I quote from [basic.lookup.argdep] / 4, my emphasis is:

When considering the associated namespace, the search is performed in the same way as the search performed when the associated namespace is used as a classifier (3.4.3.2), except that:

- Any directives used in the associated namespace are ignored.

- Any namespace name functions or friend function templates declared in related classes are visible within their respective namespaces, even if they are not visible in a normal search (11.3).

- All names except functions (possibly overloaded) and function templates are ignored.

+8
source share

All Articles