开发者

Scope of friend function in GCC

According to the standard:

A friend function defined in a class is in the (lexical) scope of the class in which it is defined.

Then why the heck doesn't this work (several versions of GCC tested)?

#include <iostream>
using namespace std;

class A
{
  friend void function() { cout << "text" << endl; };
};

// void function();

int main()
{
  function();
  return 0;
}

Uncommenting the declaration of course solves the problem.

Edit (gcc output):

(xterm) $ g++ -ansi -pedantic -Wall -Wextra test.cpp 
test.cpp: In 开发者_开发知识库function ‘int main()’:
test.cpp:13:11: error: ‘function’ was not declared in this scope


The quote means that the following works - the code is in the lexical scope of the class, such that unqualified name lookup will behave specially

class A
{
  typedef int type;

  friend void function() { 
    type foo; /* type is visible */ 
  };
};

If you had defined "function" in the namespace scope, then "type" would not be visible - you would have to say "A::type". That's why it says in the next sentence "A friend function defined outside the class is not.". Unqualified name lookup for an in-class definition is stated as

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.

So the text you quoted is not really required to be normative - the specification of unqualified name-lookup already covers it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜