超出范围的枚举转换可以产生底层类型之外的值吗? [英] Can an out-of-range enum conversion produce a value outside the underlying type?

查看:829
本文介绍了超出范围的枚举转换可以产生底层类型之外的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

#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) );
}

我的问题是:

My question is: Can the default case be triggered, i.e. this program generates output?

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

The tricky point in N3936 seems to be the specification of static_cast when converting an out-of-range integer to enumeration type, [expr.static.cast]/10:


可以将积分或枚举类型的值显式转换为枚举类型。如果原始值在枚举值的范围内,则值不变。否则,结果
值未指定(且可能不在该范围内)

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).

粗体文本没有明确说明该值必须仍然在底层类型的范围内,但我想知道它是否是它的意图。

The bolded text does not explicitly say that the value must still be within the range of the underlying type, but I am wondering if it were intended that it did.

推荐答案

我想[expr.static.cast] / 10回答这个。在当前工作草案中,它显示为:

I think [expr.static.cast]/10 answers this. In the current working draft, this reads:


整数或枚举类型的值可以显式转换为完整的枚举类型。如果原始值在枚举值(7.2)的范围内,则值不变。 否则,行为
未定义。

换句话说, ,因为具有固定底层类型(在您的情况下: bool )的枚举类型的范围是该类型的范围。

In other words, your program has undefined behaviour, since the range of an enumeration type with fixed underlying type (in your case: bool) is the range of that type.

与报价的变更受到CWG1766的解析issues link );请注意,该问题被识别为缺陷(因此您应该忘记原来的措辞)。

The change from your quote was affected by the resolution of CWG1766 (issues link); note that the issue is recognized as a defect (so you should forget the original wording).

这篇关于超出范围的枚举转换可以产生底层类型之外的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆