How to use enumeration for bitwise operations

28 03 2013

An enumeration is a user-defined type consisting of a set of named constants called enumerators. If we try to perform some bitwise operation on enum values, it will show compiler error (C2440).

The best way to resolve this issue is overloading bitwise operators(|, &, ~ etc) for enum.

    enum Colors
    {
        red = 1,
        blue,
        yellow,
        green
    };

    inline Colors operator|(Colors a, Colors b)
    {
        return static_cast(static_cast(a) | static_cast(b));
    }

    inline Colors operator&(Colors a, Colors b)
    {
        return static_cast(static_cast(a) & static_cast(b));
    }
    void main()
    {
        Colors c1 = red | blue;
        Colors c2 = red & blue;
    }

By default, the first enumerator has a value of 0, and each successive enumerator is one larger than the value of the previous one, unless you explicitly specify a value for a particular enumerator.

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: