以下代码崩溃了Microsoft编译器:
class Var
{
public:
template <typename T>
operator T () const
{ }
};
int main()
{
Var v;
switch (v)
{ }
}
我的问题:代码是否正确或编译器是否应该给出相应的错误?是否可以明确地转换为整数类型?
答案 0 :(得分:8)
编译器崩溃始终是一个错误,此代码不会在gcc
或clang
上编译,但两者都会提供错误而不会崩溃。对于clang
,错误是:
error: statement requires expression of integer type ('Var' invalid)
switch (v)
^ ~
gcc
提供了以下错误:
error: ambiguous default type conversion from 'Var'
switch (v)
^
另外,请注意,在C ++中,流出值返回函数的末尾是未定义的行为。
更新
添加:
operator int () const
{ return 0; }
该课程的会带来clang
和gcc
的不同结果。
有关gcc
或clang
是否正确的讨论,请参阅Classes with both template and non-template conversion operators in the condition of switch statement。我对N3323
的解释暗示clang is correct on this one。
提交错误报告
我filed a bug report for this ICE,到目前为止还没有回应。即使这看起来像一个奇怪的角落情况,它确实会导致内部编译器错误,应该修复。