TITLE: forward declaring friends (Newsgroups: comp.lang.c++.moderated, 20 Oct 99) CHAMBERLAND: Eric Chamberland >> [snip] >> > template >> > class A >> > { >> > friend void foo(); >> > }; >> > >> > template >> > void foo(){ >> > } >> > -------------------------- >> > >> > Whith my compiler (KAI --strict -D_KAI_STRICT v3.4d) the second >> > doesn't pass, but the first does. BUSHUYEV: Gene Bushuyev >> The syntax of your friend declaration is wrong. SHIVA: Shiva > I can't see anything wrong with his friend declaration > > template > class A > { > friend void foo(); > }; > > seems to be perfectly correct. > It means foo is a friend of A > foo is a friend of A BUSHUYEV: >> And the definition of >> the friend should precede the declaration in a template class that it >> may be found during the lookup. SHIVA: > I don't know about this but another post in the same thread by Biju > Thomas indicates that > friend decl is taken as a forward declaration. POTTER: John Potter I think that if you read that again, you will see that Biju said "yes" a forward declaration is required. The rules have changed on this along the road to the standard. C++PL3e has a recent correction to an example. The state of compilers has also changed and g++ for example accepts the old and new rules in such a mix that it is of no value in deciding what is correct. Play it safe. Forward declare the friends prior to the class that declares them as friends. I think that I have this example right. void f(); class C { friend void f(); // The f above is a friend friend void g(); // Some unknown g is a friend if it gets declared. }; void h1 () { g(); // error, there is no g in scope } void g(); // Here is that g and it is a friend void h2 () { g(); // ok, calls the friend } When parameters get involved, there are some other rules. Templates just make it messier. Practical advice. Assume that a friend declaration does not declare the function. Put the function declaration ahead of the class that makes it a friend. TRIBBLE: David R Tribble [david@tribble.com] (private correspondence) This is also a requirement if you're declaring a friend function having extern C linkage: extern "C" { int cCall(int a); } class Foo { friend int cCall(int a); ... }; The declaration of the extern C function must precede its declaration as a friend.