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