我尝试并搜索,我认为最好的解决方案是#define。基于something I found:
#define FLAGS(T) \
inline T operator |(const T s, const T e) { return (T)((unsigned)s | e); } \
inline T &operator |=(T &s, const T e) { return s = s | e; } \
inline T operator &(const T s, const T e) { return (T)((unsigned)s & e); } \
inline T &operator &=(T &s, const T e) { return s = s & e; } \
inline T operator ^(const T s, const T e) { return (T)((unsigned)s ^ e); } \
inline T &operator ^=(T &s, const T e) { return s = s ^ e; } \
inline T operator ~(const T s) { return (T)~(unsigned)s; }
这可以像这样使用:
enum some_state {
state_normal = 1 << 0,
state_special = 1 << 1,
state_somethingelse = 1 << 2,
state_none = 0,
};
FLAGS(some_state)
some_state var1;
对于 Visual Studio,可能需要这样来消除一些警告:
#pragma warning(disable: 4505) // '*' : unreferenced local function has been removed
事实上,Windows SDK 有the DEFINE_ENUM_FLAG_OPERATORS macro 可以做到这一点。
另一种方法是包装类like DEF_ENUM_FLAGS_TYPE uses。
或者使用the LLVM_MARK_AS_BITMASK_ENUM macro 之类的东西。不过,您可能需要最新的编译器。