Adrian Albert Koch
Adrian Albert Koch

Reputation: 361

Using switch case for bitwise enums

I have implemented my own typesafe bitwise enum operators following this article: http://blog.bitwigglers.org/using-enum-classes-as-type-safe-bitmasks/

Here is the enum I am talking about:

enum class OutputStream : unsigned int
    {
        None = 0,
        // Using bitshift operator (always one bit set to 1)
        Console = 1 << 0,
        File = 1 << 1,
        Other = 1 << 2
    };

In case you wonder, it's for a logging function.

Problem: I want to use the enum in a switch statement such as

switch(stream)
{
    case OutputStream::Console:
        //Do this
    case OutputStream::File:
        //Do that
    default:
        break;
}

Note that there shouldn't be a break; in between the case statements since more than one case can be true.

However, this doesn't seem to work. More precisely, when I use OutputStream::Console | OutputStream::File neither case is executed.

My only solution to this problem was this awkward looking if statement:

if((stream & OutputStream::Console) != OutputStream::None) { /*Do this*/ }
if((stream & OutputStream::File) != OutputStream::None) { /*Do that*/ }

But for me, this defeats the point of a need enum based solution. What am I doing wrong?

Upvotes: 0

Views: 2637

Answers (1)

michalsrb
michalsrb

Reputation: 4891

As other said in comments, switch is not the best way, but it is still possible to do:

for (int bit = 1; bit <= (int) OutputStream::LAST; bit <<= 1)
{
    switch((OutputStream) (bit & stream))
    {
        case OutputStream::Console:
            //Do this
            break;
        case OutputStream::File:
            //Do that
            break;

        // etc...

        // no default case no case 0!
    }
}

So basically you will iterate over all individual bits, for each test if it is present in the stream variable and jump to the appropriate case, or jump nowhere if it is 0.

But in my opinion the individual ifs are better. At least you have better control over in which order are the bits evaluated.

Upvotes: 2

Related Questions