Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ setting up "flags"

Example:

enum Flags
{
    A,
    B,
    C,
    D
};

class MyClass
{
   std::string data;
   int foo;

   // Flags theFlags; (???)
}
  • How can I achieve that it is possible to set any number of the "flags" A,B,C and D in the enum above in an instance of MyClass?

My goal would be something like this:

if ( MyClassInst.IsFlagSet( A ) ) // ...
MyClassInst.SetFlag( A ); //...
  • Do I have to use some array or vector? If yes, how?
  • Are enums a good idea in this case?
like image 965
sub Avatar asked Oct 26 '25 17:10

sub


2 Answers

// Warning, brain-compiled code ahead!

const int A = 1;
const int B = A << 1;
const int C = B << 1;
const int D = C << 1;

class MyClass {
public:
  bool IsFlagSet(Flags flag) const {return 0 != (theFlags & flag);}
  void SetFlag(Flags flag)         {theFlags |= flag;}
  void UnsetFlag(Flags flag)       {theFlags &= ~flag;}

private:
   int theFlags;
}
like image 64
sbi Avatar answered Oct 28 '25 06:10

sbi


In C, you set special (non-sequential) enum values manually:

enum Flags
{
    A = 1,
    B = 2,
    C = 4,
    D = 8
};

It is better for type-safety to use:

const int A = 1;
const int B = 2; /* ... */

because (A | B) is not one of your enum values.

like image 32
Heath Hunnicutt Avatar answered Oct 28 '25 08:10

Heath Hunnicutt