问题描述
这是constexpr 静态转换的未定义行为从 int 到作用域枚举在 C++17 中编译为非固定基础类型(作用域 枚举的相同问题).TLDR 是作用域枚举始终具有固定的基础类型(默认情况下为 int,因此您始终可以从 int 转换为作用域枚举).
This is a follow up question of Undefined behavior of constexpr static cast from int to scoped enum with non-fixed underlying type compiles in C++17 (same question for scoped enumerations).TLDR is that scoped enums always have a fixed underlying type (by default int, hence you can always cast from int to scoped enum).
我想知道以下内容是否应该在 C++17 中编译
I wonder if the following should or should not compile in C++17
enum E
{
A, B
};
constexpr E x = static_cast<E>(2);
这在 Ubuntu 20.04 上使用 GCC 9.3.0 和 Clang 10.0.0 编译.
This compiles with both GCC 9.3.0 and Clang 10.0.0 on Ubuntu 20.04.
我的问题是
- 这应该编译吗?
- 如果应该,为什么?
有关为什么我认为它不应该为 unscoped 枚举进行编译的详细推理,请参阅另一篇文章.同样的道理也适用于这个问题.
See the other post for a detailed reasoning why I think it should not compile for unscoped enums. The same reasoning applies for this question as well.
推荐答案
它不应该编译.这是一个编译器错误.它在 CWG 1766 以便在常量表达式中诊断此转换.
It should not compile. It's a compiler bug. The reason it was made undefined in CWG 1766 was so that this conversion would be diagnosed in constant expressions.
这是GCC 错误 #95701.我找不到 Clang 的开放错误.
This is GCC bug #95701. I could not find an open bug for Clang.
这篇关于在 C++17 中编译的 constexpr 从 int 到 unscoped enum 的未定义行为与非固定基础类型编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!