c++ - 在 C++ 中用逻辑 OR ("|") 分隔选项

标签 c++ bitflags

我知道可以在初始化fstream的实例时添加选项,例如:

fstream file("filename.txt", ios::in | ios::out | ios::binary);

在这种情况下,有 3 个选项。 我有几个问题:

  1. 我应该如何在我自己的职能中实现它?
  2. 我应该定义任何常量值或宏吗?
  3. 如何解析选项并正确处理它们?

最佳答案

How should I implement that in my own function?

让它成为bitmask type :

The bitmask type supports a finite number of bitmask elements, which are distinct non-zero values of the bitmask type, such that, for any pair Ci and Cj, Ci & Ci != 0 and Ci & Cj == 0. In addition, the value 0 is used to represent an empty bitmask, with no values set.


Should I define any const values or macros?

这些值通常是表示 2 的连续幂的常量,即 1、2、4、8、16 等。

How to parse the options and deal with the them properly?

你永远不需要“解析”这些选项——你需要做的就是检查给定的选项是否存在。您可以使用 & 运算符:

openmode x = ios::in | ios::out;
if (x & ios::in) {
    ... // TRUE
}
if (x && ios::binary) {
    ... // False
}

关于c++ - 在 C++ 中用逻辑 OR ("|") 分隔选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45760275/

相关文章:

c# - 用标志方法扩展枚举?

c++ - 在 C++ 中逐行读取并从行中获取单词

c++ - 关于数组类型的问题

C - 将枚举用于位标志 - 警告 : enumerated type mixed with another type

c - 如何在c中格式化标志?

java - 遍历@IntDef、@StringDef 或任何@Def 类中的值

c++ - QComboBox::showPopup()从其QLineEdit窃取焦点

c++ - 使用自定义构造函数作为模板函数

c++ - 有没有办法使成员函数不能从构造函数调用?

c - 在位域集合中检测到至少一位被设置