简体   繁体   中英

strongly typed enum classes in visual studio 11 (beta)

I'm playing around with the Visual Studio 11 Beta at the moment. I'm using a strongly typed enum to describe some flags

enum class A : uint32_t
{
    VAL1 = 1 << 0,
    VAL2 = 1 << 1,
};
uint32_t v = A::VAL1 | A::VAL2;    // Fails

When I attempt to combine them as above I get the following error

error C2676: binary '|' : 'A' does not define this operator or a conversion to a type acceptable to the predefined operator

Is this a bug with the compiler or is what I'm attempting invalid according to the c++11 standard?

My assumption had been that the previous enum declaration would be equivalent to writing

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以实现您正在执行的操作。

Strongly typed enums do not have operator | in any form. Have a look there: http://code.google.com/p/mili/wiki/BitwiseEnums

With this header-only library you can write code like

enum class WeatherFlags {
    cloudy,
    misty,
    sunny,
    rainy
}

void ShowForecast (bitwise_enum <WeatherFlags> flag);

ShowForecast (WeatherFlags::sunny | WeatherFlags::rainy);

Add: anyway, if you want uint32_t value, you'll have to convert bitwise_enum to uint32_t explicitly, since it's what enum class for: to restrict integer values from enum ones, to eliminate some value checks unless explicit static_casts to and from enum class-value are used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM