friend function definition

Hans-Christian Stadler hans-christian.stadler@psi.ch
Tue Mar 27 16:49:00 GMT 2018


Thanks a lot for clearing that up.

Now I just don't understand the text in the N4700 early version of the 
C++17 standard (under class.friend):

A function can be defined in a friend declaration of a class if and only 
if the class is a non-local class (12.4),
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 ]

Anyway, it's probably to wierd a case to spend much time on.

Thanks, HC

On 27.03.2018 17:37, Jonathan Wakely wrote:
> On 27 March 2018 at 16:32, Hans-Christian Stadler wrote:
>> I've got a piece of code which I think should be legal, but I get an error
>> with g++
>
> Any decent C++ compiler will give the same result:
>
> https://godbolt.org/g/XzoieP
>
>
>
>> #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';
>> }
>>
>>
>> stadler_h@tuxedo:~/Devel/Test/CPP$ g++ --version
>> g++ (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0
>> Copyright (C) 2017 Free Software Foundation, Inc.
>> This is free software; see the source for copying conditions. There is NO
>> warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
>>
>> stadler_h@tuxedo:~/Devel/Test/CPP$ g++ -Wall -std=c++17 tmpl_test.cc
>> tmpl_test.cc: In function ‘int main(int, char**)’:
>> tmpl_test.cc:12:18: error: ‘register_bird’ was not declared in this scope
>>       std::cout << register_bird() << '\n';
>>                    ^~~~~~~~~~~~~
>>
>> As far as my limited C++ knowledge goes, register_bird should be a valid
>> function in global scope?
> No, the friend declaration defines the function, but does not make the
> name visible in the enclosing namespace. The function can only be
> found by Argument Dependent Lookup, but because it has no arguments,
> that won't find it either.
>
> To make the function visible in the global scope you also need a
> declaration outside the class body:
>
> class bird_watch {
>      friend int register_bird() {
>          return ++bird_watch::counter;
>      }
>      static int counter;
> };
> int register_bird();



More information about the Gcc-help mailing list