Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internal compiler error - Templated conversion operator in switch expression

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?

like image 293
typ1232 Avatar asked Jul 30 '14 20:07

typ1232


1 Answers

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.

like image 88
Shafik Yaghmour Avatar answered Oct 19 '22 23:10

Shafik Yaghmour