News for hackers. Stuff that matters.
Re:Type-safe Bitmasks in C++ by pwagland on Wednesday June 13, 2018 @07:44AM (#17302163)
Nice technique, however, they don't allow you to do everything that a bitmask does. For example, there is no way to clear a flag, or to select a subset of flags.

That is, given:

  enum class Button {
    A, B, Select, Start, Up, Down, Right, Left
  };
There is no way to define:

  bitmask<Button> controller_state { Button::A | Button::B };
And then to find out if either of these buttons are pressed. The only way to do it is:

  bool fn2(bitmask<Button> controller_state)
  {
    return controller_state & Button::A || controller_state & Button::B;
  }
which _does_ generate the optimal code for checking if either is set. However you can't do something like

  void handleDirectionButtons(bitmask<Button> controller_state);
and then call that with something like:

  bitmask<Button> direction_buttons { Button::Up | Button::Down | Button::Right | Button::Left };
  handleDirectionButtons(state & directionButtons)
Of course, this could be added, see https://godbolt.org/g/48asye

You could also do something similar for the ~ case as well, however that would end up looking a bit uglier, as you would need to create more bit masks, something like:

  ~bitmask(Button::Up) & ~bitmask(Button::Down)
For an example, see https://godbolt.org/g/wN2xUV

There are no comments on this comment yet.