I don't understand why the following does not compile (e.g. in gcc 9.10 or MS VS C++ 2019):
class X {
public:
friend bool operator==(int, X const &);
};
int main() {
2 == X(); // ok...
static_cast<bool (*)(int, X const &)>(&operator==); // Error: 'operator==' not defined
return 0;
}
but the following code is compiled without any issues:
class X {
public:
};
bool operator==(int, X const &);
int main() {
2 == X(); // ok...
static_cast<bool (*)(int, X const &)>(&operator==); // OK!
return 0;
}
My expectation is that a friend function (operator==) of X behaves as a standalone function (operator==). What I'm missing? Thanks
What I'm missing?
An inline friend declaration does not make the function available to ordinary name lookup.
Pay close attention to the error. It does not say that the function is of the wrong type, it simply can't find anything named operator==
. This is by design.
Inline friend definitions are only found by argument dependent lookup. Ordinary lookup (such as naming the function to take its address), cannot find it. If you want the function to be available for that purpose, you must provide a namespace scoped declaration.
class X {
public:
friend bool operator==(int, X const &) { /* ... */ }
};
bool operator==(int, X const &);