help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

friend definitions lookup and ADL


From: John V Shahid
Subject: friend definitions lookup and ADL
Date: Thu, 12 Oct 2006 20:00:14 +0000

#include <iostream>
using namespace std;
class Friendly {
  int i;
public:
  Friendly(int theInt) { i = theInt; }
  friend void f(const Friendly&); // Needs global def.
  void g() { f(*this); }
};
void h() {
  f(Friendly(1));  // Uses ADL
}
void f(const Friendly& fo) {
  cout << fo.i << endl;
}
int main() {
  h(); // Prints 1
  Friendly(2).g();
}

this is code from thinking in c++ 2nd ed. Here bruce says that f()
(globally defined and friend of class Friendly) is looked through ADL
when used in h() (look at the commented line above).

But in the c++ standard (2nd ed.-2003), section 11.4, the 5th paragraph
says:
        A function can be defined in a friend declaration of a class if
        and only if the class is a non-local class, the function name is
        unqualified, and the function has namespace scope. [Example:
        class M {
                friend void f() { } // definition of global f, a friend
                of M,
                // not the definition of a member function
        };
        —end example] Such a function is implicitly inline. A friend
        function defined in a class is in the (lexical) scope of the
        class in which it is defined. A friend function defined outside
        the class is not (3.4.1).
///////////////////////////////////////////////////////////////////////
The point is that Bruce Eckel said if f(Friendly(1)) was replaced by
f(1) (which makes sense as Friendly can be converted from int) then the
compiler should issue an error because there's no hint for the ADL
lookup where to look. The g++ compiles the code without complaining, and
as i noticed from the standard that should be the right behavior since
f() has now global scope which will make it a candidate for the call and
subsequently force conversion of 1 to Friendly(1).

I would appreciate your comments on that.
-- 
                                                          John V. Shahid





reply via email to

[Prev in Thread] Current Thread [Next in Thread]