Re: friend function definition

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

 



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();




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux