gpt4 book ai didi

c++ - 使用枚举类定义标志

转载 作者:行者123 更新时间:2023-11-30 05:39:00 26 4
gpt4 key购买 nike

在现代 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 模式有效实践?

最佳答案

它以 cairo API 为蓝本.

对于 font_slant 我们可以看到 cairo 的等价物:

enum cairo_font_slant_t

typedef enum {
CAIRO_FONT_SLANT_NORMAL,
CAIRO_FONT_SLANT_ITALIC,
CAIRO_FONT_SLANT_OBLIQUE
} cairo_font_slant_t;

Specifies variants of a font face based on their slant.

      CAIRO_FONT_SLANT_NORMAL Upright font style, since 1.0

      CAIRO_FONT_SLANT_ITALIC Italic font style, since 1.0

      CAIRO_FONT_SLANT_OBLIQUE Oblique font style, since 1.0

对于 text_cluster_flags 我们可以看到 cairo 的等价物:

enum cairo_text_cluster_flags_t

typedef enum {
CAIRO_TEXT_CLUSTER_FLAG_BACKWARD = 0x00000001
} cairo_text_cluster_flags_t;

Specifies properties of a text cluster mapping.

      CAIRO_TEXT_CLUSTER_FLAG_BACKWARD The clusters in the cluster array map to glyphs in the glyph array from end to start. (Since 1.8)

text_to_glyphs 函数为 cairo_show_text_glyphs 建模,它接受一个 cairo_text_cluster_flags_t。此外,API 具有获取当前倾斜度的功能。所以我的猜测是:

  • enum class 用于标记的强类型。拥有既“正常”又“斜体”的东西没有任何意义。这些附加到“字体”。

  • text_cluster_flags 是一次性交易。如果您为 show glyphs 函数设置它,它只会改变行为。它不像倾斜附加到“字体”那样附加到“文本集群”。没有理由在这里使用强类型。

顺便说一句,您的解释是正确的。这是源代码的片段:

// ...

+ const cairo_glyph_t *cur_glyph;
+
+ if (cluster_flags & CAIRO_TEXT_CLUSTER_FLAG_BACKWARD)
+ cur_glyph = glyphs + num_glyphs - 1;
+ else
+ cur_glyph = glyphs;
+
+ for (i = 0; i < num_clusters; i++) {
+ cairo_bool_t cluster_visible = FALSE;
+

// ...

关于c++ - 使用枚举类定义标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32531924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com