The following code crashes the Microsoft compiler:
class Var
{
public:
template <typename T>
operator T () const
{ }
};
int main()
{
Var v;
switch (v)
{ }
}
My question: Is the code correct or should the compiler give an appropriate error? Is an unambiguous conversion to an integral type possible?
The compiler crashing is always a bug, this code does not compile on either gcc
or clang
but both provide an error without crashing. For clang
the error is:
error: statement requires expression of integer type ('Var' invalid)
switch (v)
^ ~
gcc
provides the following error:
error: ambiguous default type conversion from 'Var'
switch (v)
^
Also, note that flowing off the end of a value returning function is undefined behavior in C++.
Update
Adding:
operator int () const
{ return 0; }
to the class brings about different results from clang
and gcc
.
See Classes with both template and non-template conversion operators in the condition of switch statement for a discussion on whether gcc
or clang
is correct. My interpretation of N3323
implies clang is correct on this one.
Filed bug report
I filed a bug report for this ICE, so far no response. Even though this seems like an odd corner case it does cause an internal compiler error which should be fixed.
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