Internal compiler error - Templated conversion operator in switch expression

不打扰是莪最后的温柔 提交于 2019-12-23 09:48:19

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/25046418/internal-compiler-error-templated-conversion-operator-in-switch-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!