我想使用范围格式的枚举,但是能够在枚举和无符号整数之间进行比较和赋值。
这是我尝试过的下面的代码,它可以正常工作:
class SystemEvents {
public:
enum {
Opened, Closed
};
};
class OtherEvents {
public:
enum {
Closed,Opened
};
};
//test
uint32_t e = SystemEvents::Opened;
if(e == OtherEvents::Closed) std::cout << "enums are weakly typed and scoped";
但是我想知道是否可以使用C ++ 11语法做到这一点?
enum class SystemEvents : uint32_t {
Opened,Closed
};
enum class OtherEvents : uint32_t {
Closed,Opened
};
//test
uint32_t e = SystemEvents::Opened;
if(e == OtherEvents::Closed) std::cout << "enums are weakly typed and scoped";
上面的代码给了我预期的错误Cannot initialize a variable of type int with an rvalue of type SystemEvents
。因此,我应该坚持使用C风格的范围枚举,还是在C ++ 11中有办法做到这一点?还是有其他方法可以做到这一点?
对于初始化,除了强制转换值外,您无能为力。请注意,C ++ 11的强类型枚举并不是要替换现有的枚举,而是对其进行补充。如果您想要一个弱类型的枚举,请不要使用enum class
。
为了比较强类型的枚举,可以声明必要的运算符并在实现内部进行强制转换:
bool operator==( uint32_t lhs, SystemEvents rhs )
{
return static_cast< SystemEvent >( lhs ) == rhs;
}
当然,您需要两个方向:
bool operator==( SystemEvents lhs, uint32_t rhs );
和其他运算符一样!=
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句