Implement C # style flags in C ++

2

I am adapting the maze generator algorithm written in C # to C ++.

I have found a new theme for me: Flags I know how to implement enumerators in c ++, it's practically the same, but I do not understand how to implement the flags.

In concrete this is the flag:

[Flags]
public enum CellState
{
    Top = 1,
    Right = 2,
    Bottom = 4,
    Left = 8,
    Visited = 128,
    Initial = Top | Right | Bottom | Left,
}

I have done the enumerator:

public enum CellState {
    Top = 1,
    Right = 2,
    Bottom = 4,
    Left = 8,
    Visited = 128,
    };

How should I implement the flags in c ++?

    
asked by SalahAdDin 04.03.2017 в 18:17
source

2 answers

2

You could do something like this:

#include <iostream>

using namespace std; 

enum CellState{
    Top = 1,
    Right = 2,
    Bottom = 4,
    Left = 8,
    Visited = 128,
    Initial = Top | Right | Bottom | Left
};

int main(void){

    CellState estado = Top;

    if(estado & Initial){
        cout << "Celda Initial" << endl;
    }else{
        cout << "Celda NOT Initial" << endl;
    }

    return 0;
}

Result

  

Initial Cell

When implementing the flags in the same enumerator:

Top | Right | Bottom | Left

We can do the extraction of a value different from them using the operator:

& - > Just an ampersand

For this we apply the instruction:

if(estado & Initial)

Returns true as long as the value is different from those of the flag (flag).

    
answered by 04.03.2017 в 18:29
1

A fairly convenient way to keep these listed is to create them from binary shifts:

enum CellState
{
  Top.    = 1 << 0,
  Right   = 1 << 1,
  Bottom  = 1 << 2,
  Left    = 1 << 3,
  Visited = 1 << 7,
  TopLeft = Top | Left,
};

As I am writing from the mobile, which is tedious, and its use is exactly the same as the one commented in the response of @IvanBotero for the moment I do not add examples of use. If they are necessary I add them when I am in front of the computer .

    
answered by 05.03.2017 в 12:24