内部编译器错误 - 切换表达式中的模板化转换运算符

时间:2014-07-30 20:34:10

标签: c++ templates switch-statement implicit-conversion

以下代码崩溃了Microsoft编译器:

class Var
{
public:
    template <typename T>
    operator T () const
    { }
};

int main()
{
    Var v;
    switch (v)
    { }
}

我的问题:代码是否正确或编译器是否应该给出相应的错误?是否可以明确地转换为整数类型?

1 个答案:

答案 0 :(得分:8)

编译器崩溃始终是一个错误,此代码不会在gccclang上编译,但两者都会提供错误而不会崩溃。对于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; }
该课程的

会带来clanggcc的不同结果。

有关gccclang是否正确的讨论,请参阅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,到目前为止还没有回应。即使这看起来像一个奇怪的角落情况,它确实会导致内部编译器错误,应该修复。