在现代 C++ 中使用枚举作为标志的适当模式是什么?
这个问题源于我对技术规范A Proposal to Add 2D Graphics Rendering and Display to C++的阅读,其中 McLaughlin、Sutter 和 Zink 提出了基于Cairo API 的用于 2D 图形的 C++ API。
在整个 API 声明中,作者充分利用了 C++11。特别是,它们的枚举都被声明为:
enum class font_slant {
normal,
italic,
oblique
};
除了一个:
namespace text_cluster_flags {
enum text_cluster_flags : int {
none = 0x0,
backward = 0x1
};
}
“text_cluster_flags
类型”用于类方法中:
void show_text_glyphs(const ::std::string& utf8,
const ::std::vector<glyph>& glyphs,
const ::std::vector<text_cluster>& clusters,
text_cluster_flags cluster_flags);
我假设无关的声明是text_cluster_flags
可以掩盖的,如:
auto flag = text_cluster_flags::none | text_cluster_flags::backward;
你不能用enum class
枚举来做:
enum class flags {
a = 0x0,
b = 0x1
};
auto f = flags::a | flags::b; // error because operator `|` is
// not defined for enum class flags
// values
作者是否应该定义屏蔽运算符?或者他们的enum-within-namespace模式是有效的实践吗?