mandatory pre-declaration of friend function?

This works well on GCC despite "The C++ Programming Language 3rd ed."
p 280 appears to say it can't:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

namespace test
{
   class X
   {
      friend void f();
      static const int i = 1;
   };

   void f()
   {
      std::cout << X::i << std::endl;
   }
}

class X
{
   friend void f();
   static const int j = 3;
};

void f()
{
   std::cout << X::j << std::endl;
}

int
main()
{
   f();
   test::f();

   //test::X::i; // error
   //X::j; // error

   return 0;
}

Book says, it won't work, except if f() was declared before X! So what is correct as of C++03 standard?
Did you mean to make those members public?
No. To declare void f(); into each namespace *before* writing friend void f();!
Whoa! That was a dumb question on my part. Friends...duh.
As far as I can tell the Standard C++03 says it is legal unless your class is local in which case a forward declaration is required:

11.4.3 A function first declared in a friend declaration has external linkage (3.5). Otherwise, the function retains its previous linkage (7.1.1).

11.4.9 If a friend declaration appears in a local class (9.8) and the name specified is an unqualified name, a prior declaration is looked up without considering scopes that are outside the innermost enclosing non-class scope. For a friend function declaration, if there is no prior declaration, the program is ill-formed. For a friend class declaration, if there is no prior declaration, the class that is specified belongs to the innermost enclosing non-class scope, but if it is subsequently referenced, its name is not found by name lookup until a matching declaration is provided in the innermost enclosing nonclass scope.

Topic archived. No new replies allowed.