Why does this code not compile ? I would have expected that the built-in unary operator& would have been selected, such that the ambiguity between the two binary operator& should not matter. If you comment out one of the binary operator&, the code compiles (with gcc 11.2) and the built-in unary operator& is selected.
struct A
{ int operator&(int) const { return 1; }
};
struct B
{ int operator&(int) const { return 2; }
};
struct C : A, B
{};
C* test(C& c)
{ return &c; } //error: request for member 'operator&' is ambiguous
Problem is overload resolution. First function name should be matched and if abutting is found error should be reported. After that matching of arguments is performed. Here is an example with regular function: https://godbolt.org/z/nYfjdn1Td
As you can see ambiguity is reported for foo on all compilers even although both foos have different number of arguments.
Same issue should pop up for operator& so more like gcc is right here.
Overload resolution is a complex topic. Usually you do not have to think about it. Here is nice source which explains how complex this is.
If you wish to fix problem and have binary operator available for such code, you can do this:
struct C : A, B
{
using A::operator&;
using B::operator&;
};
This fixes problem with your test on all compilers.
of course ambiguity for instaceOfC & intValue remains, but you can resolve it by doping one using statement.
https://godbolt.org/z/ds3W4GYcT
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