1

I defined a getline function inside my own namespace:

namespace pru{
class A{
    friend std::istream& getline(std::istream& in, A& a)
    {
         std::cout << "getline\n";
         return in;
     }
 };

And then call it in the main as usual:

pru::A a;
pru::getline(std::cin, a);

But surprisingly it doesn't compile. Both g++ and clang gives the same error:

'getline' is not a member of 'pru'

But if I call getline without pru:

pru::A a;
getline(std::cin, a);

it compiles!!! Why? getline is a member of pru!

Antonio
  • 579
  • 1
  • 3
  • 12
  • 1
    Possible duplicate of [What's the scope of inline friend functions?](https://stackoverflow.com/questions/8207633/whats-the-scope-of-inline-friend-functions) – GBlodgett May 12 '19 at 16:49

1 Answers1

1

This answer should explain everything. I will just give explanation for your particular example. Friend functions that are declared/defined inside a class are part of the enclosing namespace (in this case pru). But they are not visible by (un)qualified lookup unless they are at least declared in that namespace too. Since you did not declare it explicitly, this code won't compile:

pru::A a;
pru::getline(std::cin, a);

Had you done this:

namespace pru{
class A{
    friend std::istream& getline(std::istream& in, A& a)
    {
         std::cout << "getline\n";
         return in;
     }
 };
 std::istream& getline(std::istream& in, A& a);//Can be placed anywhere in pru.
}

The above could would also work. As the answer states the friend functions are visible by ADL. You can read more about it e.g. here. It basically means that because the arguments are from std and pru namespaces then they are also searched for getline declaration.

Quimby
  • 17,735
  • 4
  • 35
  • 55
  • Do you happen to know why the standards committee made the decision to add friend functions to the enclosing namespace without making them available for qualified lookup with the namespace name? When I first saw this it... really caught me by surprise – Alecto Irene Perez May 12 '19 at 16:48
  • @J.AntonioPerez I have no idea, I think that would make a good question. – Quimby May 12 '19 at 16:50