C++ list all enumerated flags independently

162 views Asked by At

I currently have a set of enums being used as flags

enum Flags {
    Flag1 = 1
    Flag2 = 2
    Flag3 = 4
    Flag4 = 8
};

So on and so forth. I'm then using an inline to make it so the | to allow them to be combined. Using this system I can then check for independent flags using simple if statements.

Printing combined flags in this manner produces their sum, ie: Flag2 | Flag4 would produce 10.

My question is if there's a way to list all of the flags currently assigned to something as independent ints instead of their combined sum.

2

There are 2 answers

0
akakatak On

How about this?

#include <cstdint>
#include <bitset>

enum Flags
{
    Flag0 = 1
  , Flag1 = 2
  , Flag2 = 4
  , Flag3 = 8
};

using FlagBits = std::bitset<4>;

int main ()
{
    FlagBits flgs(Flag1 | Flag2);
    for (int i = 0; i < flags.size(); ++i) {
        bool flg = flgs[i];
        // ...
    }
};
0
AudioBubble On

Yes.

enum Flags {
Flag1 = 1,
Flag2 = 2,
Flag3 = 4,
Flag4 = 8,
};

uint32_t my_flags = Flag1 | Flag2;

if(my_flags & Flag1) { cout << "I have flag 1" << endl; }
if(my_flags & Flag2) { cout << "I have flag 2" << endl; }

// etc.

Is that what you meant?