gpt4 book ai didi

c++ - 类型转换在存储受限的枚举中失败

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:36 26 4
gpt4 key购买 nike

SSCCE :

enum class confirm {yes};

struct item
{
confirm s:4; // (1) limiting storage size required
};

int main()
{
item itm;

itm.s = confirm::yes; // (2) OK

switch (itm.s)
{
case confirm::yes: // (3) Failure, need static data cast here?
break;
}
}

产生错误:

In function ‘int main()’:
error: could not convert ‘yes’ from ‘confirm’ to ‘int’
case confirm::yes:
^

虽然用 g++ 编译,但用 clang++ 编译得很好。 为什么标记为 (2) 的赋值是可能的,而标记为 (3) 的case 子句不是?

关于存储空间太小的警告是offtopic

最佳答案

这看起来像一个 gcc 错误,我们可以看到它有效 in the latest gcc version :

来自 C++11 标准草案 6.4.2 [stmt.switch]:

The condition shall be of integral type, enumeration type, or of a class type for which a single non-explicit conversion function to integral or enumeration type exists (12.3). [...] Integral promotions are performed. Any statement within the switch statement can be labeled with one or more case labels as follows:

case constant-expression :

where the constant-expression shall be a converted constant expression (5.19) of the promoted type of the switch condition.

转换后的常量表达式在 5.19 节中介绍:

[...]A converted constant expression of type T is a literal constant expression, implicitly converted to type T, where the implicit conversion (if any) is permitted in a literal constant expression and the implicit conversion sequence contains only user-defined conversions, lvalue-to-rvalue conversions (4.1), integral promotions (4.5), and integral conversions (4.7) other than narrowing conversions (8.5.4). [ Note: such expressions may be used as case expressions (6.4.2), as enumerator initializers if the underlying type is fixed (7.2), and as integral or enumeration non-type template arguments (14.3). —end note ] [...]

也许这与defect report 1767: Scoped enumeration in a switch statement有关.所以也许它强制提升为 int,然后在这种情况下比较会失败。

关于c++ - 类型转换在存储受限的枚举中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32253075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com