How can I use an enum class in a boolean context?

后端 未结 7 1939
醉酒成梦
醉酒成梦 2021-01-07 15:59

I have some generic code that works with flags specified using C++11 enum class types. At one step, I\'d like to know if any of the bits in the flag are set. Cu

7条回答
  •  攒了一身酷
    2021-01-07 16:46

    If you have a flags field (ie: a bitfield) I would strongly advise you not to use enum class for bitfields.

    Strongly typed enums exist to be, well, strongly typed. It makes the enumerators into something more than just named constant integers the way regular enums are. The idea is that, if you have a variable of an enum class type, then its contents should always exactly match one of the enumerator values. That's why there is no implicit conversion from or to integer types.

    But that's not what you're doing. You're taking a bitfield, which is a composition of enumerator values. That composition is not itself any one of those values; it's a combination of them. Therefore, you're lying when you say that you're taking the enum class type; you're really just taking an unsigned integer that might be one of the enum class enumerators.

    For example:

    enum class Foo
    {
      First   = 0x01,
      Second  = 0x02,
      Third   = 0x04,
    };
    
    Foo val = Foo::First | Foo::Second;
    

    val in this case does not contain First, Second, or Third. You've lost strong typing, because it doesn't contain any of the types.

    enum class values cannot be implicitly converted to bool; they cannot be implicitly converted to integers; and they cannot implicitly have most math operations performed on them. They are opaque values.

    And thus they are inappropriate for use as bitfields. Attempting to use enum class in such an inappropriate way will only lead to a lot of casting. Just use a regular old enum and save yourself the pain.

提交回复
热议问题