6

$11.4/5 - "[...]A friend function defined in a class is in the (lexical) scope of the class in which it is defined[...]"

What does this statement mean?

struct A{
   typedef int MYINT;
   void f2(){f();}                    // Error, 'f' is undefined
   friend void f(){MYINT mi = 0;}     // Why does this work, shouldn' it be A::MYINT?
   void f1(){f();}                    // Error, 'f' is undefined
};

int main(){}
  1. What is confusing here is that the call to 'f' from 'A::f1' is quiet understandable. However why is call to 'f' from 'A::f2' ill-formed, when a friend is in 'lexical' scope of the befriending class? What does 'lexical' scope mean?

  2. At the same type why is the usage of 'MYINT' in 'f' OK? Shouldn't it be 'A::MYINT'?

If I add a parameter of type 'A *' to 'f', then both 'f1' and 'f2' are able to find 'f' because of ADL. This is understandable.

Chubsdad
  • 23,089
  • 4
  • 57
  • 108
  • 2
    is in the (lexical) scope means it has access to containing scope. hence MYINT is valid. http://stackoverflow.com/questions/1047454/what-is-lexical-scope, http://stackoverflow.com/questions/991518/c-how-do-i-call-a-friend-template-function-defined-inside-a-class – Anycorn Sep 03 '10 at 03:22

2 Answers2

1

You have quoted only part of §11.4/5. According to it f() should be declared out of class first (function should have namespace scope). Try this:

void f(); // declare it first
struct A{
   typedef int MYINT;
   void f2(){f();}                    
   friend void f(){MYINT mi = 0;}     // definition of global f, a friend of A
   void f1(){f();}                    
};

As for second question, it is ok because of quoted by you part of §11.4/5. f() obeys the same rules for name binding as a static member function of that class and has no special access rights to members of an enclosing class.

Kirill V. Lyadvinsky
  • 89,955
  • 22
  • 127
  • 208
0

Here is my interpreation of one part of my query which is

"Why MYINT" can be referred to as "MYINT" instead of "A::MYINT"?

$3.4.1/9 states - "Name lookup for a name used in the definition of a friend function (11.4) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions. If the friend function is not defined in the class granting friendship, name lookup in the friend function definition shall proceed as described for lookup in namespace member function definitions."

In our case, the name to be looked up is 'MYINT' which is a unqualified name. The lookup for this name inside the definition of the friend 'f' which is defined inline in the class would would be done in the same was as it would be for member functions of 'A'.

Is my understanding correct?

Chubsdad
  • 23,089
  • 4
  • 57
  • 108