I have this simple C++ program:
#include <iostream>
struct obj {
  friend int f(int);
  void m(int x) { std::cout << "f(" << x << ") = " << f(x) << std::endl; }
};
int main() {
  obj o;
  o.m(21);
}
int f(int x) {
  return 2*x;
}
If I compile with the GNU C++ compiler g++, I get the error prog.cpp:7:55: error: 'f' was not declared in this scope
However, if I compile it with cl (and /W4) it compiles and executes fine.
I am not sure which compiler is correct.
From cppreference on friend declaration:
A name first declared in a friend declaration within class or class template X becomes a member of the innermost enclosing namespace of X, but is not visible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided
A matching declaration at global scope is provided, but only after the definition of obj::m(). I think it's correct to refuse the call to f at this point. You can see the effect e.g. this compiles with both gcc and clang,
int f(int);
class obj { /* as before... */ };
and so does this:
struct obj {
  friend int f(int);
  void m(int x); 
};
int f(int);
void obj::m(int x) { std::cout << "f(" << x << ") = " << f(x) << std::endl; }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With