I don't understand what is going on in the following piece of code:
struct A { };
struct B {
B() { }
B(const A&) { }
friend B operator*(const B&, const B&)
{
return B();
}
};
int main()
{
B x = A() * A();
return 0;
}
When I compile (with both clang and gcc 4.9.2) I get an error message on the "B x = A() * A()" line; clang says "invalid operands to binary expression".
If I take the operator* definition from inside the class, everything is 100% ok!
struct A { };
struct B {
B() { }
B(const A&) { }
friend B operator*(const B&, const B&);
};
B operator*(const B&, const B&)
{
return B();
}
int main()
{
B x = A() * A();
return 0;
}
What is going on?
1 个答案:
答案 0 :(得分:3)
Since operator*() is defined inside the function as a friend, it can only be found by ADL, not normal unqualified lookup. This type of lookup requires that the arguments be exact types, not types that are implicitly convertible. This means the operator cannot be found even if A can be converted to B.
When you declare the function outside the class, then it can be found by the normal unqualified lookup rules.