在 C++ 中用逻辑或(“|”)分隔选项

Separating options with logical OR ("|") in C++

我知道可以在初始化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?

您永远不需要 "parse" 这些选项 - 您需要做的就是检查给定选项是否存在。您可以使用 & 运算符:

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

这些是位掩码。

How should I implement that in my own function?

Should I define any const values or marcos?

不需要宏。我更喜欢枚举:

namespace options {
    enum options_enum : unsigned {
        in       = (1u << 0),
        out      = (1u << 1),
        binary   = (1u << 2),
        whatever = (1u << 3),
    };
};

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

通过屏蔽:

bool in = option_argument & options::in;