枚举的基础 int 是否有保证宽度?
在 N2347 的示例中,新强类型枚举 (C++11) 与当前 (C++03) 相比的一个优势是通过一个“旧”枚举的示例来解释的:
enum Version { Ver1 = 1, Ver2 = 2 };
struct Packet {
Version ver;
// ... more data ...
// bad, size can vary by implementation
Version getVersion() const { return ver; }
};
我想知道:这里的“变化”意味着编译器甚至可以选择一种8位表示形式,即枚举元素仅占用一个单词?或者是否有最小长度保证并且选择只能在int
和long
之间?
换句话说,如果我有一个像这样的 Version
枚举:
enum VersionXyz { Ver1 = 100, Ver2 = 200 };
struct Packet {
VersionXyz ver;
// ... more data ...
};
这是否可能只需要 Packet
中的 8bit
。软件更新后:
enum VersionXyz { Ver1 = 100, Ver2 = 200, Ver3=300 };
现在 Packet
不再具有相同的大小,因为枚举已增长?
In the example in N2347 one advantage if the new stongly typed enums (C++11) compared the current (C++03) is explained by an example with an "old" enum:
enum Version { Ver1 = 1, Ver2 = 2 };
struct Packet {
Version ver;
// ... more data ...
// bad, size can vary by implementation
Version getVersion() const { return ver; }
};
I wonder: means "varying" here that the compiler can even choose a 8bit representation, i.e. that the enum-elements occupy only one word? Or is there a minimum length guaranteed and the choice may only be between int
and long
?
In other words, if I have a Version
enum like this:
enum VersionXyz { Ver1 = 100, Ver2 = 200 };
struct Packet {
VersionXyz ver;
// ... more data ...
};
Is it possible that this takes only 8bit
in Packet
. And after a software update to:
enum VersionXyz { Ver1 = 100, Ver2 = 200, Ver3=300 };
now Packet
has not the same size anymore because the enum has grown?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++03 标准的相关段落是 §7.2.5:
所以它是实现定义的。唯一可以保证的是,如果您定义一个所有值都适合 int 的枚举,则枚举类型的大小不会大于 int。 (但是由于
int
的大小也是实现定义的,所以这并没有给你太多信息。)The relevant paragraph of the C++03 standard is §7.2.5:
So it's implementation defined. The only thing you are guaranteed is that if you define an enum where all values fit into an
int
, then the enumeration type's size won't be greater thanint
. (But sinceint
's size is also implementation-defined, that doesn't give you much.)如果您知道您的枚举列表只会达到一定的大小,那么在使用时可能值得对其进行类型转换,并且还可以断言是否超过了该大小,至少这就是我在发送数据包时使用枚举的方式
If you know that your enum list is only ever going to be a certain size it might be worth type casting it when used, and also have an assert for if that size is ever exceeded, at least thats how I use enums when sending packets