在超过第 32 个标志后,我的 enum
一直面临问题:
enum ConditionType_t {
CONDITION_NONE = 0,
CONDITION_LIGHT = 1 << 0,
CONDITION_INFIGHT = 1 << 1,
CONDITION_MUTED = 1 << 2,
...
CONDITION_LUCKY = 1 << 32,
}
知道 enums
基本上是 8bit
,CONDITION_LUCKY
将等于 CONDITION_NONE
。所以我实现了 C++11
的 enum classes
:
enum class ConditionType_t : uint64_t {
CONDITION_NONE = 0,
CONDITION_LIGHT = 1 << 0,
CONDITION_INFIGHT = 1 << 1,
CONDITION_MUTED = 1 << 2,
...
CONDITION_LUCKY = 1 << 32,
}
现在我收到数百万条警告,例如:
warning C4293: '<<' : shift count negative or too big, undefined behavior
错误如:
error C2065: 'CONDITION_NONE' : undeclared identifier
显然,位移位与枚举类
不相容。
有什么想法吗?
最佳答案
表达式1 << 32
是未定义的行为。来自 [expr.shift]:
The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.
自 1
是一个 int
,它只有 32 位。即使这不是未定义的,你也不会得到你想要的值,因为 1 << 32
的类型是int
,无论如何都不能保存 33 位值。
您需要使用 uint64_t
从头开始:
enum class ConditionType_t : uint64_t {
CONDITION_NONE = 0,
CONDITION_LIGHT = 1ULL << 0,
CONDITION_INFIGHT = 1ULL << 1,
CONDITION_MUTED = 1ULL << 2,
...
CONDITION_LUCKY = 1ULL << 32,
};
关于c++ - 带位的长枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38558083/