说,我有以下结构:
typedef struct my_struct{
unsigned long a;
unsigned long b;
char* c;
unsigned int d1 :1;
unsigned int d2 :4;
unsigned int d3 :4;
unsigned int d4 :23;
} my_type, *p_type;
字段 d3
当前由 #define
定义从 0x00
到达的直到 0x0D
.
其实,d3
是一个枚举。所以很想继续替换
unsigned int d3 :4;
通过
my_enum d3 :4;
这是安全/允许的吗?
代码必须用各种编译
- 编译器(GCC、Visual Studio、嵌入式)
- 平台(Win32、Linux、嵌入式)
- 配置(编译为 C,编译为 C++)
显然,我可以保留 d3
的定义。照原样并在我的代码中使用枚举,将其分配给 d3
等等,但这不适用于 C++。
最佳答案
在所有支持标准的 C++ 编译器中都允许。
C++03 标准 9.6/3
A bit-field shall have integral or enumeration type (3.9.1). It is implementation-defined whether a plain (neither explicitly signed nor unsigned) char, short, int or long bit-field is signed or unsigned.
C++03 标准 9.6/4
If the value of an enu- merator is stored into a bit-field of the same enumeration type and the number of bits in the bit-field is large enough to hold all the values of that enumeration type, the original enumerator value and the value of the bit-field shall compare equal.
例子
enum BOOL { f=0, t=1 };
struct A {
BOOL b:1;
};
void f() {
A a;
a.b = t;
a.b == t // shall yield true
}
但你不能认为枚举具有无符号基础类型。
C++03 标准 7.2/5
The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enu- merator cannot fit in an int or unsigned int
关于c++ - 在位字段中使用枚举是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11983231/