本文介绍了C ++ 0x中的C ++枚举的底层类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试着阅读一些C ++标准来了解枚举的工作原理。

I've been trying to read a bit of the C++ standard to figure out how enum's work. There's actually more there than I originally thought.

对于范围枚举,很清楚底层类型是 int

For a scoped enumeration, it's clear that the underlying type is int unless otherwise specified with an enum-base clause (it can be any integral type).

enum class color { red, green, blue};  // these are int

对于无范围的枚举,看起来像底层类型可以是任何整数类型

For unscoped enumerations, it seems like the underlying type can be any integral type that will work and that it won't be bigger than an int, unless it needs to be.

enum color { red, green, blue};  // underlying type may vary

由于底层类型的无范围的枚举不是标准化的,处理序列化实例的一个?到目前为止,我写的时候已经转换为 int ,然后序列化到 int 并设置我的 enum 变量在开关中读取,但似乎有点笨重。有更好的方法吗?

Since the underlying type of unscoped enumarations are not standardized, what's the best way of dealing with serializing instances of one? So far, I've been converting to int when writing then serializing into an int and setting my enum variable in a switch when reading, but it seems a bit clunky. Is there a better way?

enum color { red, green, blue };
color c = red;
// to serialize
archive << (int)c;
// to deserialize
int i;
archive >> i;
switch(i) {
  case 0: c = red; break;
  case 1: c = green; break;
  case 2: c = blue; break;
}


推荐答案

C ++ 0x的东西,所以我不能评论。

I haven't read any C++0x stuff so I couldn't comment on that.

对于序列化,你不需要开关读取枚举 - 到枚举类型。

As for serializing, you don't need the switch when reading the enum back in - just cast it to the enum type.

但是,我在写入流时不投射。这是因为我经常喜欢写一个运算符<<

However, I don't cast when writing to the stream. This is because I often like to write an operator<< for the enum so I can catch bad values being written, or I can then decide to write out a string instead.

enum color { red, green, blue };
color c = red;

// to serialize
archive << c;    // Removed cast

// to deserialize
int i;
archive >> i;
c = (color)i;    // Removed switch

这篇关于C ++ 0x中的C ++枚举的底层类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 13:43