JOK
JOK

Reputation: 135

Operator overloading enum class

I'm trying to overload the & operator of an enum class, but I'm getting this compiler error: error: no match for 'operator&=' (operand types are 'int' and 'Numbers'). Any ideas about this?

#include <iostream>
using namespace std;

enum class Numbers : int
{
    zero                    = 0, 
    one                     = 0x01,
    two                     = 0x02
};

inline int operator &(int a, Numbers b)
{
    return ((a) & static_cast<int>(b));
}

int main() {
    int a=1;
    a&=Numbers::one;
    cout << a ;
    return 0;
}

Upvotes: 3

Views: 3088

Answers (3)

The compiler is telling exactly what's wrong. You didn't overload &=.

Despite the expected semantics, &= doesn't automatically expand to a = a & Numbers::one;

If you want to have both, the canonical way is to usually implement op in terms of op=. So your original function is adjusted as follows:

inline int& operator &=(int& a, Numbers b)
{ // Note the pass by reference
    return (a &= static_cast<int>(b));
}

And the new one uses it:

inline int operator &(int a, Numbers b)
{ // Note the pass by value
    return (a &= b);
}

Upvotes: 6

Bathsheba
Bathsheba

Reputation: 234665

Nice question but your tremendously helpful compiler diagnostic tells you everything you need to know.

You are missing the *bitwise AND assignment operator" : operator&=.

Upvotes: 1

Martin B.
Martin B.

Reputation: 1663

Yes you are overloading the operator &. But then you are using the operator &= which is a different one. Overload that too and you'll be fine.

Upvotes: 0

Related Questions