Setting Up Option Parameters :: C++

kuphryn

Senior member
Jan 7, 2001
400
0
0
Hi.

I would like to create a generic class that wraps around, say, an API function. I need a way to pass into a function parameters such as FEATURE1 | FEATURE3. I believe that requires the use of bitwise AND, OR, and NOT similar to MFC programming style.

For example:

-----
// call function to initialize variables

SetVariableA(FEATURE1 | FEATURE 3) // I want feature1 and feature3
-----

Here is what SetVariableA(...) might look like

-----
enum STYLE {FEATURE1 = 0, FEATURE2, FEATURE3}

SetVariableA(...)
{
}
-----

Basically, I am not familiar with the use of enum with bitwise AND, OR, and NOT. Here is a what I would like to accomplish.

- user calls function to setup a feature: function(FEATURE1)
- function determines what feature the user wants

How would you implement some like the above using enum, bitwise AND, OR, and NOT?

Thanks,
Kuphryn

P.S. MFC programmers seem
 

Adrian Tung

Golden Member
Oct 10, 1999
1,370
1
0
Basically, you're doing bit manipulation. A DWORD has 32 bits, which allows you to set up to 32 different flags. So, you'll be declaring your flag constants as numbers that represent each bit position, i.e. 1, 2, 4, 8, 16, 32, 64, etc.

The easiest way to do this is with a shift function:

typedef enum
{
eFLAG_MYFLAG1 = 1,
eFLAG_MYFLAG2 = (1 << 1),
eFLAG_MYFLAG3 = (1 << 2),
} enFLAGS;

So in your function call, you'll just need to declare a DWORD input variable, i.e.

void MyFunc(DWORD dwFlags);

Then you can easily pass in your flags using bitwise OR:

myClass.MyFunc(eFLAG_MYFLAG1 | eFLAG_MYFLAG2);

In your function, you can check the flags by doing a bitwise AND:

if (dwFlags & eFLAG_MYFLAG1)
{
// do something
}
else if (dwFlags & eFLAG_MYFLAG2)
{
// do something else
}
// etc.

You can also define simple macros to do flag setting and checking if you want to. i.e.

#define CHECKFLAG(fl, x) (fl & x)
#define SETFLAG(fl, x) (fl | x)


Hope that helps,
:)atwl