Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c++ - Friend function is not visible in the class

I have the following code:

struct M {
    friend void f() {}
    M() {
        f(); // error: 'f' was not declared in this scope
    }
};

int main() {
    M m;
}

Live example

Both g++4.8 and clang3.4 fail to compile it, because f is not visible inside M, or so they say.

However, the Standard gives an example of a similar code

class M {
  friend void f() { } // definition of global f, a friend of M,
                      // not the definition of a member function
};

and says that

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

(ISO/IEC 14882:2011 11.3 Friends [class.friend] p6, p7)

From this I can't understand how compiler can't find f which is defined in same class where it's used.

It's kinda unlikely that both compilers have the same bug.
So, what did I miss?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The friend declaration states that a function called f in the surrounding namespace is a friend of the class; but it does not introduce the name f into the namespace. It's not available (except by argument-dependent lookup) until it's been declared in the namespace.

The relevant rule is C++11 7.3.1.2/3:

If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup or by qualified lookup until a matching declaration is provided in that namespace scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...