Are enums the canonical way to implement bit flags?

后端 未结 3 2022
死守一世寂寞
死守一世寂寞 2021-02-19 04:30

Currently I\'m using enums to represent a state in a little game experiment. I declare them like so:

namespace State {
  enum Value {
    MoveUp = 1 << 0,          


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-02-19 04:54

    I believe that your approach is right (except several things):
    1. You can explicitly specify underlying type to save memory;
    2. You can not use unspecified enum values.

    namespace State {
      enum Value : char {
        None      = 0,
        MoveUp    = 1 << 0, // 00001 == 1
        MoveDown  = 1 << 1, // 00010 == 2
        MoveLeft  = 1 << 2, // 00100 == 4
        MoveRight = 1 << 3, // 01000 == 8
        Still     = 1 << 4, // 10000 == 16
        Jump      = 1 << 5
      };
    }
    

    and:

    State::Value state = State::Value::None;
    state = State::Value(state | State::MoveUp);
    if (mState & State::MoveUp) {
      movement.y -= mPlayerSpeed;
    }
    

    about overloading:

    inline State::Value& operator|=(State::Value& a, State::Value b) {
        return a = static_cast (a | b);
    }
    

    and since you use C++11, you should use constexpr every were is possible:

    inline constexpr State::Value operator|(State::Value a, State::Value b) {
        return a = static_cast (a | b);
    }
    
    inline constexpr State::Value operator&(State::Value a, State::Value b) {
        return a = static_cast (a & b);
    }
    

提交回复
热议问题