c++ - How to overload |= operator on scoped enum? -


how can overload |= operator on typed (scoped) enum (in c++11, gcc)?

i want test, set , clear bits on typed enums. why typed? because books practice. means have static_cast<int> everywhere. prevent this, overload | , & operators, can't figure out how overload |= operator on enum. class you'd put the operator definition in class, enums doesn't seem work syntactically.

this have far:

enum class numerictype {     none                    = 0,      padwithzero             = 0x01,     negativesign            = 0x02,     positivesign            = 0x04,     spaceprefix             = 0x08 };  inline numerictype operator |(numerictype a, numerictype b) {     return static_cast<numerictype>(static_cast<int>(a) | static_cast<int>(b)); }  inline numerictype operator &(numerictype a, numerictype b) {     return static_cast<numerictype>(static_cast<int>(a) & static_cast<int>(b)); } 

the reason this: way works in strongly-typed c#: enum there struct field of underlying type, , bunch of constants defined on it. can have integer value fits in enum's hidden field.

and seems c++ enums work in exact same way. in both languages casts required go enum int or vice versa. however, in c# bitwise operators overloaded default, , in c++ aren't.

inline numerictype& operator |=(numerictype& a, numerictype b) {     return a= |b; } 

this works? compile , run: (ideone)

#include <iostream> using namespace std;  enum class numerictype {     none                    = 0,      padwithzero             = 0x01,     negativesign            = 0x02,     positivesign            = 0x04,     spaceprefix             = 0x08 };  inline numerictype operator |(numerictype a, numerictype b) {     return static_cast<numerictype>(static_cast<int>(a) | static_cast<int>(b)); }  inline numerictype operator &(numerictype a, numerictype b) {     return static_cast<numerictype>(static_cast<int>(a) & static_cast<int>(b)); }  inline numerictype& operator |=(numerictype& a, numerictype b) {     return a= |b; }  int main() {     // code goes here     numerictype a=numerictype::padwithzero;     a|=numerictype::negativesign;     cout << static_cast<int>(a) ;     return 0; } 

print 3.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -