我想在范围格式中使用枚举,但能够在枚举和无符号整数之间进行比较和赋值。
这是我尝试了下面的代码,它按预期工作:
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";
上面的代码给了我预期的错误无法用 SystemEvents 类型的右值初始化 int 类型的变量
。那么,我应该坚持使用 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 );
和其他运算符,如 !=
。
关于c++ - 作用域但 "semi-weakly"类型枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21205403/