Operator Overloading for Composite Assignment Operators on Enumerations
There is a lot of information, examples, etc. to overload operators of all kinds on the Internet. But I can't for the life of me find an example on how to do this for a simple enumeration and, say, operators |=
or +=
.
With a, the bitwise or
implementation is as follows:
inline MyEnum operator | (MyEnum a, MyEnum b)
{
return (MyEnum)((int)a | (int)b);
}
All the examples I found are for compound operations, but for classes; which can easily take a pointer this
for the LHS. In the enum I don't have that, so what's the correct syntax?
Update : I've 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 value bitwise or
.
source to share
Based on your update, the implementation and signature need to change slightly:
inline MyEnum& operator |= (MyEnum& a, MyEnum b)
// ^ here and ^ here
{
return a = (MyEnum)((int)a | (int)b);
}
For the operation to work as expected, it is important that the signature matches the inlines , and it would generally be recommended that the implementation correlate as well. The signatures can be obtained from the reference listed in the comments (canonical in this case T1& operator |= (T1& lhs, T2 const& rhs)
.
The links here ( MyEnum&
) are important (especially for MyEnum& a
), so the operator behaves like an inline in one, and that would be how you would expect it to be.
Pay attention to the type of return ; return type can be of any type, even void
. This will affect what could be compiled. For example, with a return of the type above, MyEnum c = (a |= b);
will compile. On return void
it won't, but a |= b;
it will still compile. It is recommended that returns match inline, as this will give you more natural semantics.
source to share