如何使枚举类与'bit-or'功能一起使用?
How to make enum class to work with the 'bit-or' feature?
我通常将enum
与"bit-or"或|
一起使用,以允许对象有一些选项。如何使枚举类与"位或"功能一起使用?
您需要重载枚举类的运算符,并通过强制转换为底层类型来实现它们:
enum class foo : unsigned {
bar = 1,
baz = 2
};
foo operator |(foo a, foo b) {
return static_cast<foo>(static_cast<unsigned>(a) | static_cast<unsigned>(b));
}
。当然,这可以推广(使用SFINAE和std::underlying_type
)。在我看来,C++没有提供开箱即用的这个是一个疏忽。
下面是一般实现的外观:
// Intentionally undefined for non-enum types.
template <typename T, bool = std::is_enum<T>::value>
struct is_flag;
template <typename T>
struct is_flag<T, true> : std::false_type { };
template <typename T, typename std::enable_if<is_flag<T>::value>::type* = nullptr>
T operator |(T lhs, T rhs) {
using u_t = typename std::underlying_type<T>::type;
return static_cast<T>(static_cast<u_t>(lhs) | static_cast<u_t>(rhs));
}
// … same for `&`, `~`. And maybe functions like `isset`, `set` and `unset`.
此实现可确保仅为实际充当标志的枚举找到重载。要将枚举标记为标志,您需要专门is_flag
:
enum class a_flag : unsigned {
foo = 0,
bar = 1,
baz = 2
};
template <> struct is_flag<a_flag> : std::true_type { };
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 当直接分配时,为什么此功能指针分配起作用,而不是与有条件的操作员一起使用
- pcap_dump功能在与pcap_loop一起使用时不会被调用,pcap_dispatch始终返回 0
- 如何将BITMAPV5HEADER与CreateDIBitmap功能一起使用
- 将打开的CV的重映射功能与类型CV_8SC1的源图像一起使用
- 如何使此功能与 FILE 一起使用?C++
- 删除功能误差的C 与有条件的iniaization一起使用
- 重新分配指针后,将类功能与指针一起使用
- GCC vs Clang:将功能与-FPIC一起插入
- C 与查找功能一起使用时,迭代器为什么行为会有所不同
- 当与可能导致缓冲区溢出的功能一起使用时,外部变量是否比其他变量更大
- 如何声明 IP 地址以将其与多种功能一起使用
- 如何将QProgressDialog与QDomDocument保存功能一起使用
- 如何将unordered_set与比较功能一起使用
- 如何使枚举类与'bit-or'功能一起使用?
- 使用_GLIBCXX_CXX11_ABI将5.1版以前的C++ABI与C++11/14功能一起使用有什么意义
- 是否可以将STL复制功能与地图一起使用
- 如何将 Doxygen 的 "Documentation at other places" 功能与专门的模板类一起使用?