In the following code struct A
has two implicit conversion operators to char
and int
, and an instance of the struct is compared for equality against integer constant 2
:
struct A {
constexpr operator char() { return 1; }
constexpr operator int() { return 2; }
};
static_assert( A{} == 2 );
The code passed fine in GCC and MSVC, but Clang complains:
<source>:5:20: error: use of overloaded operator '==' is ambiguous (with operand types 'A' and 'int')
static_assert( A{} == 2 );
~~~ ^ ~
<source>:5:20: note: because of ambiguity in conversion of 'A' to 'float'
<source>:2:15: note: candidate function
constexpr operator char() { return 1; }
^
<source>:3:15: note: candidate function
constexpr operator int() { return 2; }
^
<source>:5:20: note: built-in candidate operator==(float, int)
static_assert( A{} == 2 );
^
<source>:5:20: note: built-in candidate operator==(double, int)
<source>:5:20: note: built-in candidate operator==(long double, int)
<source>:5:20: note: built-in candidate operator==(__float128, int)
<source>:5:20: note: built-in candidate operator==(int, int)
...
Demo: https://gcc.godbolt.org/z/h9Kd66heM
The general question is which compiler right here? And in particular it is interesting to know why Clang does not prefer operator==(int, int)
, however lists it among others?
float
comparison here at all? – Christogramrhs, lhs
iflhs, rhs
has been defined ... but ... hmm, sounds scary. I probably remember wrong. – Mexicali==
normal function overloadsf(float, int)
andf(int, int)
are considered in a callf(A{}, 2)
, then GCC agrees that it is ambiguous, while MSVC still accepts. – Nahuatlan