我在 Visual Studio 2013(调试/Win32 编译)下观察到以下行为。考虑以下 c++ 代码:
#include <iostream>
#include <climits>
int main(int argc, char *argv[])
{
enum { V = (unsigned long long)ULLONG_MAX } E;
std::cout << sizeof E << std::endl;
enum : unsigned long long { W = (unsigned long long)ULLONG_MAX } F;
std::cout << sizeof F << std::endl;
return 0;
}
编译后会导致:
$ ./enum.exe
4
8
如果我正确理解了 c++ 标准 (Standard C++ 7.2/5),则这是无效的 c++ 行为。在这种情况下,我不应该被要求显式定义底层类型,因为枚举器的值不适合 int
或 unsigned int
。
所以:
- 这是 Visual Studio 2013 众所周知的限制吗(可能其他版本会受到影响)?
- 有没有办法强制编译器为 c++98 风格的枚举使用正确的底层类型?还是我需要切换到具有固定类型的 c++11 表示法?
更新:按照建议,我在以下位置报告了一个问题:
最佳答案
引用说明如下(重要部分加粗):
Declares an unscoped enumeration type whose underlying type is not fixed (in this case, the underlying type is an implementation-defined integral type that can represent all enumerator values; this type is not larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0).
和
Values of unscoped enumeration type are implicitly-convertible to integral types. If the underlying type is not fixed, the value is convertible to the first type from the following list able to hold their entire value range: int, unsigned int, long, unsigned long, long long, or unsigned long long. If the underlying type is fixed, the values can be converted to their promoted underlying type.
综合来看,很明显这是 msvc 的错误。 (可能在某个时候引入)。更糟糕的是,它有点对此保持沉默。
关于c++ - 无范围枚举的基础类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55574977/