Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ inline friend function with same name as member variable

This surprised me. This works:

struct foo {
  int x;
  friend int x(foo f) { return f.x; }
  friend int y(foo f);
};

int y(foo f) { return x(f); } // no problem

But this is an error:

struct foo {
  int x;
  friend int x(foo f) { return f.x; }
  friend int y(foo f) { return x(f); } // error: invalid use of foo::x data member
};

Why aren't both of these (dis)allowed?

like image 237
dmitchell Avatar asked Oct 21 '22 04:10

dmitchell


1 Answers

The reason is that in the first case, the friendship injected the function declaration into the enclosing namespace, so the global-scoped call to x can see only one x.

In the second example, x has two meanings at that scope: The global friend function and the variable (which presumably shadows the global friend function).

like image 113
Mark B Avatar answered Nov 12 '22 22:11

Mark B