我现在正在玩Visual Studio 11 Beta。我正在使用强类型枚举来描述一些标志
enum class A : uint32_t
{
VAL1 = 1 << 0,
VAL2 = 1 << 1,
};
uint32_t v = A::VAL1 | A::VAL2; // Fails
当我尝试如上所述组合它们时,出现以下错误
error C2676: binary '|' : 'A' does not define this operator or a conversion to a type acceptable to the predefined operator
这是编译器的错误还是根据 c++11 标准我尝试的内容无效?
我的假设是,之前的枚举声明等同于写入
struct A
{
enum : uint32_t
{
VAL1 = 1 << 0,
VAL2 = 1 << 1,
};
};
uint32_t v = A::VAL1 | A::VAL2; // Succeeds, v = 3
强类型枚举不能隐式转换为整数类型,即使其底层类型是 uint32_t
,您需要显式转换为 uint32_t
以实现您正在做的事情。
强类型枚举没有任何形式的运算符|
。看看那里: http://code.google.com/p/mili/wiki/BitwiseEnums
使用此仅标头库,您可以编写类似
enum class WeatherFlags {
cloudy,
misty,
sunny,
rainy
}
void ShowForecast (bitwise_enum <WeatherFlags> flag);
ShowForecast (WeatherFlags::sunny | WeatherFlags::rainy);
添加:无论如何,如果你想要uint32_t值,你必须显式地将bitwise_enum转换为uint32_t,因为这是枚举类的用途:限制枚举值的整数值,消除一些值检查,除非使用显式static_casts到枚举类值和从枚举类值。