强制 enum 为 unsigned long 类型
是否可以强制枚举的基础类型为 unsigned long 类型?谢谢
Is it possible to force the underlying type of an enumeration to be unsigned long type? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C++11 及更高版本中,您可以显式提及您想要的类型:
这将允许您显式控制基础类型。
在 C++03 中,无法强制枚举类型具有任何特定的底层实现。引用 C++03 规范,§7.2/5:
这是一个相当宽松的条件,它表明您不仅不一定知道该类型,而且因为它是实现定义的,所以无法保证它甚至根本对应于一种基本类型。
In C++11 and higher, you can explicitly mention what type you want:
This will allow you to explicitly control the underlying type.
In C++03, there is no way to force an enumerated type to have any particular underlying implementation. Quoth the C++03 spec, §7.2/5:
This is a pretty lax condition and says that not only can you not necessarily know the type, but because it's implementation-defined there's no guarantee that it even corresponds to one of the primitive types at all.
这可以根据您的编译器来实现。
它不适用于 Windows MSVS,但我测试了它,它适用于以下版本的 gcc/g++(加上嵌入式 cpp)编译器:
通过将一个枚举定义为一个以 long 值表示的值,在某些编译器中它会强制它达到该大小。下面的代码通常输出:
来源:
This can be achieved depending on your compiler.
It doesn't work with windows MSVS, but I tested it and it worked with the following versions of the gcc/g++ (plus embedded cpp) compiler:
By defining one of your enumerations to a value that would be represented in a long value, in some compilers it forced it to that size. The below code generally outputs:
Source:
从 C++11 开始,您可以像这样执行
enum MyEnum : unsigned long
:参考:此处
Since C++11 you can do
enum MyEnum : unsigned long
like this:Reference: here