Consider:
struct Y {
Y(float f) : f(f) {}
float f;
};
struct X {
X(Y y) : i(y.f) {}
int i;
friend bool operator==(X x1, X x2) {
return x1.i == x2.i;
}
};
int main()
{
return Y(1) == Y(2); // ERROR
}
This causes the following error on MSVC and a similar one on Clang:
'==': candidate function(s) not accessible
could be the friend function at '..\main.cpp(11)' : '==' [may be found via argument-dependent lookup]
If I move the definition of the friend function out of the class:
struct X {
X(Y y) : i(y.f) {}
int i;
friend bool operator==(X x1, X x2);
};
inline bool operator==(X x1, X x2)
{
return x1.i == x2.i;
}
The expression in main() above compiles fine.
Is this mandated by the standard or a bug? If it's mandated: why?
This is a C++ oddity.
[C++14: 11.3/7]:[..] A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (3.4.1).
This means that the operator call would work if you made it from within a member function, but not otherwise. Even though it's not a member.
Argument-dependent lookup is about the only other way to call it, but that's useless to you here because both arguments are Xs, not Ys.
Your workaround is the best way to do it, and avoids this mess (as you've seen).
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