Enum class bitwise operator overloading for reference type

54 views Asked by At

Tested my code here:

https://godbolt.org/z/Pb9nhq6jE

I have an enum defined like this.

enum Color
{
    Red = 0 << 0,
    Blue = 1 << 0,
    Green = 2 << 0,
};

I want to overload one of the bitwise operators

Color& operator |= (Color& a, Color b)

These two overloads work as expected

Color& operator |= (Color& a, Color b)
{ 
    return (Color&)((int&)a |= (int)(b)); 
}
Color& operator |= (Color& a, Color b)
{ 
    a = static_cast<Color>(static_cast<int64_t>(a) | static_cast<int64_t>(b));
    return a;
}

However, if I do the following way, the compiler complains
:22:22: error: invalid 'static_cast' from type 'Color' to type 'int&'

Color& operator |= (Color& a, Color b)
{ 
    return (Color&)((static_cast<int64_t&>(a)) |= (int64_t)(b)); 
}

But I am unsure why overloading works for c style casting (1st method) but compiler complains about static_cast. As far as I understand, from compiler's standpoint, c-style casting and the static_cast keyword should basically compile the same way.

0

There are 0 answers