Carlton Banks Carlton Banks - 10 months ago 41
C++ Question

Generate state based on values of struct member function

I am currently trying to come up with a pretty solution that generates an integer based state, based on a struct.

struct status{
* @brief busy
* true = Currently handling a message in manual mode
* false = Not handling
bool busy;
* @brief speed
* Variable containing the current speed
* Speed possibilities [FAST;MEDIUM;SLOW]
int speed;
* @brief powered
* A boolean determining whether it is powered or not.
* true = ON
* false = OFF
bool powered;
* @brief direction
* A boolean determing the direction
* true = FORWARD
* false = BACKWARDS
bool direction;


The function need to take an instance of the struct in, and generate a unique state based on member variables.

What is a pretty solution that doesn't involve manually checking, or setting up all the possibilities an thereby generate the state?

Answer Source

You can use a bitset (either std::bitset or an unsigned numerical type) to represent your unique state.

You will need:

  • 1 bit for busy.
  • 1 bit for powered.
  • 1 bit for direction.
  • 2 bits for speed.

In total, you will need 5 bits to represent all possible combinations.


auto status::hash() const noexcept
    std::bitset<5> b;
    b |= speed; // assumes only the last two bits in `speed` are used
    b.set(4, busy);
    b.set(3, powered);
    b.set(2, direction);
    return b;

wandbox example