friend function definition

Matthias Kretz m.kretz@gsi.de
Tue Mar 27 15:36:00 GMT 2018


On Dienstag, 27. März 2018 17:32:11 CEST Hans-Christian Stadler wrote:
> I've got a piece of code which I think should be legal, but I get an
> error with g++
> 
> #include <iostream>
> 
> class bird_watch {
>      friend int register_bird() {
>          return ++bird_watch::counter;
>      }
>      static int counter;
> };
> 
> int main (int argc, char *argv[])
> {
>      std::cout << register_bird() << '\n';
> }
> 
> As far as my limited C++ knowledge goes, register_bird should be a valid
> function in global scope?

No, it's in the scope of bird_watch. It's a so-called "private friend" (apart 
from being actually private in the snippet you show). Those functions can only 
be found via ADL. Example:

struct A {
  friend void f(A) {}
};

void g() {
  f(A());  // looks in the scope of A because of the argument
}

Cheers,
  Matthias

-- 
──────────────────────────────────────────────────────────────────────────
 Dr. Matthias Kretz                                https://kretzfamily.de
 GSI Helmholtzzentrum für Schwerionenforschung             https://gsi.de
 SIMD easy and portable                     https://github.com/VcDevel/Vc
──────────────────────────────────────────────────────────────────────────


More information about the Gcc-help mailing list