Click to See Complete Forum and Search --> : Array of enum elements!
Jose Juan
March 16th, 2004, 06:38 AM
Hi all, I hope some of you can help me.
I have defined an enum with different possible events
typedef enum _TEvent
{
event1 = (1uL<<1),
event2 = (1uL<<2),
event3 = (1uL<<4)
} TEvent;
And now I want to define an Array in which each element is a mask of the elements of the enumeration, for example:
TMask[0] = event1 | event3;
Tmask[1] = event2 | event3;
Tmask[2] = event1;
Etc…
Now I will receive an event and I have to see if it is part of the mask
For (int i=0; i<Tmasksize; i++)
{
if (event & Tmask[i])
{
}
}
How can I define this array? Thanks in advance for you answers, I really appreciate it!
Jose.
Guysl
March 16th, 2004, 07:50 AM
not sure what you need, but could this help you?
typedef enum _TMask
{
mask1 = event1 | event3,
mask2 = event2 | event3,
mask3 = event1
} TMask;
TMask masks[10]={mask1,mask2,mask3/*...*/};
dude_1967
March 16th, 2004, 07:55 AM
Jose,
In addition to the suggestion from guysl, you might get some ideas from the sample below. There are some weaknesses of the design such as the requirement that enum is as large as UINT32. However, there is something to get you started.
Sincerely, Chris.
:)
typedef enum TEvent_
{
none = 0,
event1 = 1uL << 1,
event2 = 1uL << 2,
event3 = 1uL << 4
}
TEvent;
static const TEvent EventMasks[] =
{
static_cast<TEvent>(event1 | event3),
static_cast<TEvent>(event2 | event3),
static_cast<TEvent>(event1)
};
// Dummy function for example purposes.
const TEvent GetEvent(void)
{
return none;
}
int main(int argc, char* argv[])
{
for(int i = 0; i < sizeof(EventMasks) / sizeof(EventMasks[0]); i++)
{
const TEvent event = ::GetEvent();
if(event & EventMasks[i])
{
// Whatever action needed.
}
}
return 0;
}
Jose Juan
March 16th, 2004, 08:18 AM
Oh thanks, this is exactly what I need.
I was a little bit confused and I wanted to find the best way to solve the problem.
Sie haben ein Bier verdient! ;-)
Guysl
March 16th, 2004, 08:24 AM
dude_1967,
nice code, though I wouldn't cast enum.
By using the cast, we miss the type-forcing of the compiler.
Its much easy to maintain enums that you can see
their legal values in its decleration, then casted
enums.
IMHO, the use of casted enum is the same as using,
in this example, const integers for events, and
an array of const integers for masks.
Guy
dude_1967
March 16th, 2004, 08:27 AM
Yeah.
Indeed, the casting of the enumerated type is a weakness of the design. Some consistent use of constants or possible even old-fashioned defines (although often frowned upon) would probably improve the overall design.
It 'll get there...
Sincerely, Chris.
:thumb:
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.