是否可以将范围枚举(“枚举类”)上下文地转换为布尔? [英] Is it possible to make a scoped enumeration ("enum class") contextually convertible to bool?

查看:125
本文介绍了是否可以将范围枚举(“枚举类”)上下文地转换为布尔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有

 枚举类标志:std :: uint16_t 
{
无= 0,
A = 0x0001,
B = 0x0002,
C = 0x0004
}

内联标志运算符|(标志lhs,标志rhs)
{
return static_cast< Flags>(static_cast< std :: uint16_t>(lhs)| static_cast< std :: uint16_t>(rhs));
}

内联标志运算符&(标志lhs,Flags rhs)
{
返回static_cast< Flags>(static_cast< std :: uint16_t>(lhs)& ; static_cast< std :: uint16_t>(rhs));
}

内联标志运算符| =(Flags& lhs,Flags rhs)
{
return lhs = lhs | RHS;
}

内联标志运算符&(=(Flags& lhs,Flags rhs)
{
return lhs = lhs& RHS;
}

是否可以使枚举类上下文转换为bool以允许某人do

 标志f = / * ... * /; 
if(f& Flags :: A){
// Do A things
}


解决方案

我不认为你可以提供转换运算符到 bool ,因为没有真正的该类的实例,但您可以重载其他运算符。自然的将是 operator!

  bool operator!(Flags f){
return f == Flags :: None;
}

然后你的程序会做:

  if(!!(f& Flags :: A)){

这是真的不自然,但对别人来说这并不奇怪(至于意义何以,他们可能会因双重否定而感到困惑)。



替代方案,您可以将该操作实现为命名函数,使其更易于阅读:

  bool test f,Flag mask){
return !!(f& mask);
}
if(test(f,Flags :: A)){...

然后再次,如果你真的想要隐式转换,为什么你首先使用枚举类?


Let's say I have

enum class Flags : std::uint16_t
{
    None = 0,
    A    = 0x0001,
    B    = 0x0002,
    C    = 0x0004
}

inline Flags operator|(Flags lhs, Flags rhs)
{
    return static_cast<Flags>(static_cast<std::uint16_t>(lhs) | static_cast<std::uint16_t>(rhs));
}

inline Flags operator&(Flags lhs, Flags rhs)
{
    return static_cast<Flags>(static_cast<std::uint16_t>(lhs) & static_cast<std::uint16_t>(rhs));
}

inline Flags operator|=(Flags& lhs, Flags rhs)
{
    return lhs = lhs | rhs;
}

inline Flags operator&=(Flags& lhs, Flags rhs)
{
    return lhs = lhs & rhs;
}

Is it possible to make the enum class contextually convertible to bool to allow someone to do

Flags f = /* ... */;
if (f & Flags::A) {
    // Do A things
}

解决方案

I don't think you can provide a conversion operator to bool, as there is no real instance of the class, but you can overload other operators. The natural one would be operator!:

bool operator!(Flags f) {
   return f == Flags::None;
}

Then your program would do:

if (!!(f & Flags::A)) {

Which is really not natural but it would not be horribly surprising to others (as of what it means, they would probably be puzzled by the double negation).

Alternative, you can implement the operation as a named function to make it more readable:

bool test(Flag f, Flag mask) {
   return !!(f & mask);
}
if (test(f,Flags::A)) { …

Then again, if you really want implicit conversions, why are you using an enum class in the first place?

这篇关于是否可以将范围枚举(“枚举类”)上下文地转换为布尔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆