c++ - 为什么在前向声明时必须提供枚举的大小?

标签 c++ c++11 enums forward-declaration

我只是不明白为什么枚举的大小与编译器相关,而类的大小却不相关。

我的代码示例:

class A;
enum E;   // must be enum E : int; in order to compile 

void f(const A & param);
void f(const E & param);

我在这里谈论的是标准 C++ 编译器。 我知道 MSVC 让它编译并且工作正常。所以问题是:

为什么这还没有标准化?

最佳答案

这已经标准化了,proposal 2764: Forward declaration of enumerations (rev. 3)如果您指定了基础类型,则允许枚举的前向声明,而在此之前这是不可能的。

主要原因是,当未指定基础类型时,大小是实现定义的,并且可能取决于枚举器值。来自草案 C++11 标准部分 7.2 [dcl.enum]:

For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be 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.

当按值传递时,不知道底层类型是一个问题是有道理的,但是当它是指针或引用时为什么它是一个问题?这很重要,因为在某些架构上,char*int* 可以有不同的大小,如 comp.lang.c++ discussion: GCC and forward declaration of enum 中所述。 :

[...] While on most architectures it may not be an issue, on some architectures the pointer will have a different size, in case it is a char pointer. So finally our imaginary compiler would have no idea what to put there to get a ColorsEnum*[...]

我们有以下 stackoverflow 答案供引用,它描述了 char* can be larger than int* 的情况,这支持了上述讨论中的断言。

一些 more details on the possible sizes of pointers看起来 char *void * 是这里的两个主要异常(exception),因此其他对象指针不应该有同样的问题。所以看起来这种情况最终是枚举独有的。

关于c++ - 为什么在前向声明时必须提供枚举的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29035225/

相关文章:

c++ - Wind River Workbench 3.3 中具有数据类型的枚举

c# - 枚举作为 ASP.NET Core WebAPI 中的必填字段

c++在一个函数参数中使用按位或 "|"的多个枚举

c++ - 链接时奇怪的 undefined reference

c++ - 如何有效地按第二个值对 vector 对进行分组?

c++ - 为什么必须在 C++ 类定义中声明方法?

c++ - 如何在C++11中高效返回大数据

c++ - gcc编译的二进制文件大小不同?

c++ - Sfinae on 具有零或一个参数的函数

c - C中的这些枚举有什么区别?