+-
c – 超出范围的枚举转换是否可以产生基础类型之外的值?
考虑以下:

#include <iostream>

enum class E : bool { A, B };

void foo(E e)
{
    switch(e)
    {
    case E::A: break;
    case E::B: break;
    default: std::cout << "aha\n";
    }
}

int main()
{
    foo( static_cast<E>(3) );
}

我的问题是:是否可以触发默认情况,即此程序是否会生成输出?

在将超出范围的整数转换为枚举类型[expr.static.cast] / 10时,N3936中的棘手问题似乎是static_cast的规范:

A value of integral or enumeration type can be explicitly converted to an enumeration type. The value is unchanged if the original value is within the range of the enumeration values. Otherwise, the resulting
value is unspecified (and might not be in that range).

粗体文本没有明确说明该值必须仍然在基础类型的范围内,但我想知道它是否打算这样做.

最佳答案
我认为[expr.static.cast] / 10会回答这个问题.在目前的工作草案中,这是:

A value of integral or enumeration type can be explicitly converted to a complete enumeration type. The value is unchanged if the original value is within the range of the enumeration values (7.2). Otherwise, the behavior
is undefined.

换句话说,您的程序具有未定义的行为,因为具有固定基础类型的枚举类型的范围(在您的情况下:bool)是该类型的范围.

报价的变化受到resolution of CWG1766(issues link)的影响;请注意,该问题被视为缺陷(因此您应该忘记原始措辞).

点击查看更多相关文章

转载注明原文:c – 超出范围的枚举转换是否可以产生基础类型之外的值? - 乐贴网