【问题标题】:typedef and enum or enum classtypedef 和 enum 或 enum 类
【发布时间】:2013-07-24 01:35:33
【问题描述】:

我有一个这样的枚举:(其实就是一个枚举类)

enum class truth_enum {
    my_true = 1,
    my_false = 0
};

我希望能够将 my_true 暴露给全局命名空间,以便我可以这样做:

char a_flag = my_true;

或者至少:

char a_flag = (char)my_true;

而不是这个:

char a_flag = truth_enum::my_true;

这可能吗?

我尝试过这样的事情:

typedef truth_enum::my_true _true_;

我收到错误:枚举类 truth_enum 中的 my_true 没有命名类型

我的猜测是 my_true 是一个值而不是一个类型。是否有其他方法可以在我的程序中启用此功能?

不理想,但我可以这样做:

enum class : const char { ... };
const char const_flag_false = truth_enum::my_false;

【问题讨论】:

  • 如果你使用枚举类,你不能避免写前缀。冗长不是问题,除非它妨碍可读性。
  • enum class 的枚举数不会隐式转换为整数,因此char a_flag = my_true; 无论如何都是错误的。
  • 我使用了上面的转换

标签: c++ c++11 enums typedef enum-class


【解决方案1】:

enum 定义中删除class。我假设你被隐式转换为int 冒犯了。怎么样:

static constexpr truth_enum _true_ = truth_enum::my_true;
static constexpr truth_enum _false_ = truth_enum::my_false;

或者干脆

const truth_enum _true_ = truth_enum::my_true;
const truth_enum _false_ = truth_enum::my_false;

【讨论】:

  • 好的,我会调查这一秒,我需要在我记得的时候修复我的代码
  • 静态上下文是做什么的?实际上,conexpr 是做什么的?
  • constepxr应用于变量使其成为const 并强制编译器在编译时计算其初始化程序。在这种特定情况下,它与const 基本相同——我可能在它可以工作但并非真正必要的地方过度使用了华丽的新结构。
  • 好的,我喜欢这样,但有必要吗?一旦我删除了class 关键字,它就编译得非常好。我可以使用my_true 而不使用truth_enum::my_true - 我应该能够这样做吗?
  • 显然我上面描述的是枚举的预期行为,而不是枚举类。
【解决方案2】:

解决方法很简单,我犯的错误是使用enum class 而不是枚举。

是的,实际上还是有点困惑 - 我现在可以使用以下值:

bool aboolean = (bool)my_true;

不必这样做:

bool aboolean = (bool)truth_enum::my_true;

这是为什么?

【讨论】:

  • C++ 中的枚举继承自 C,它几乎只是一个预处理器宏。因此,它在全局命名空间中可见。
猜你喜欢
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-15
相关资源
最近更新 更多