Underlying type of an unscoped enum?

时间:2019-04-08 13:47:50

标签: c++ visual-studio-2013

I am observing the following behavior under Visual Studio 2013 (Debug/Win32 compilation). Consider the following c++ code:

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

After compilation this leads to:

$ ./enum.exe
4
8

If I understand the c++ standard correctly (Standard C++ 7.2/5), this is an invalid c++ behavior. In this case, I should not be required to define the underlying type explicitly, since the value of an enumerator cannot fit in an int or unsigned int.

So:

  1. Is this is a well known limitation of Visual Studio 2013 (maybe other versions are affected) ?
  2. Is there a way to force the compiler to use a proper underlying type for a c++98 style enum ? Or am I required to switch to c++11 notation with fixed-type ?

Update: as suggested I reported a problem at:

1 个答案:

答案 0 :(得分:1)

参考文献中的内容如下(重要部分以粗体显示):

  

声明一个非范围枚举类型,其基础类型不是   固定的(在这种情况下,基础类型是实现定义的   可以代表所有枚举器值的整数类型;这种类型是   不得大于int ,除非枚举器的值不能适合   int或unsigned int 。如果枚举器列表为空,则基础   类型就像枚举有一个值为0的枚举)。

  

无作用域枚举类型的值可以隐式转换为   整数类型。如果基础类型不是固定的,则值为   可转换为以下列表中的第一种类型,可以容纳   它们的整个值范围:int,unsigned int,long,unsigned long,long   或 unsigned long long 。如果基础类型是固定的,则   值可以转换为其提升的基础类型。

总的来说,很明显,这是的一个错误(可能是在某个时候引入的)。更糟糕的是,对此他们保持沉默。