Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator overloading for compound assignment operators on enums

Tags:

c++

enums

There's a lot of information, examples etc. for operator overloading of all kinds on the web. But I can't for the life of me find an example on how to do this for a simple enum and, say, the |= or the += operators.

For a bitwise or the implementation is this:

  inline MyEnum operator | (MyEnum a, MyEnum b)
  {
    return (MyEnum)((int)a | (int)b);
  }

All the examples I found for compound operations however are for classes; which can easily take the this pointer for the LHS. In an enum I don't have that, so what's the correct syntax?

Update: I have already tried this version:

  inline MyEnum operator |= (MyEnum a, MyEnum b)
  {
    return (MyEnum)((int)a | (int)b);
  }

and it compiles, but doesn't return the correct bitwise or value.

like image 375
Mike Lischke Avatar asked Feb 03 '26 14:02

Mike Lischke


1 Answers

Based on your update, the implementation and signature needs to be tweaked a little;

inline MyEnum& operator |= (MyEnum& a, MyEnum b)
//           ^ here and           ^ here
{
  return a = (MyEnum)((int)a | (int)b);
}

To get the operation to work as expected, it is important that the signature correlates with the built in ones and it would generally be advised that the implementation correlates as well. Signatures can be obtained from the reference listed in the comments (the canonical in this case is T1& operator |= (T1& lhs, T2 const& rhs).

The references here (MyEnum&) are important (especially for MyEnum& a), such that the operator behaves as a built in one would, and this would be how you would expect it to.

Note the return type; the return type can be any type, even void. This would affect what would be able to be compiled. For example, with the return type above, MyEnum c = (a |= b); would compile. With a void return, it would not, but a |= b; would still compile. It is advised that the return matches the built in ones as this will give you more natural semantics.

like image 196
Niall Avatar answered Feb 05 '26 03:02

Niall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!