Re: "Reusable" operator overloading for enum?
Hi,
nick wrote:
inline ParserMode operator|(ParserMode p1, ParserMode p2)
{
return (ParserMode)((int)p1 | (int)p2);
};
...
you won't come around to use macros in this case.
E.g.
#define FLAGSATTRIBUTE(T) \
inline static T operator|(T l, T r) \
{ return (T)((unsigned)l|r); } \
inline static T operator&(T l, T r) \
{ return (T)((unsigned)l&r); } \
inline static T& operator|=(T& l, T r) \
{ return l = (T)((unsigned)l|r); } \
inline static T& operator&=(T& l, T r) \
{ return l = (T)((unsigned)l&r); } \
inline static T operator*(bool l, T r) \
{ return (T)(l*(unsigned)r); } \
inline static T operator*(T l, bool r) \
{ return (T)((unsigned)l*r); } \
inline static T operator~(T a) \
{ return (T)~(unsigned)a; }
and possibly
#define CLASSFLAGSATTRIBUTE(T) \
inline friend T operator|(T l, T r) \
{ return (T)((unsigned)l|r); } \
inline friend T operator&(T l, T r) \
{ return (T)((unsigned)l&r); } \
inline friend T& operator|=(T& l, T r) \
{ return l = (T)((unsigned)l|r); } \
inline friend T& operator&=(T& l, T r) \
{ return l = (T)((unsigned)l&r); } \
inline friend T operator*(bool l, T r) \
{ return (T)(l*(unsigned)r); } \
inline friend T operator*(T l, bool r) \
{ return (T)((unsigned)l*r); } \
inline friend T operator~(T a) \
{ return (T)~(unsigned)a; }
for private or protected nested enums.
enum ParserMode
{
PM_NONE = 0,
PM_READY = 1, // ready for next col or row, or EOF
PM_EMPTY = 2, // empty cell
PM_CELL = 4, // cell
PM_QCELL = 8, // quoted cell
PM_HEAD = 16, // header cell
};
FLAGSATTRIBUTE(ParserMode)
The result is similar than the FlagsAttribute class in DotNET.
Marcel