【问题标题】:Convert scoped enum to underlying type [duplicate]将作用域枚举转换为基础类型
【发布时间】:2020-02-07 03:20:54
【问题描述】:

给定一个作用域枚举,是否可以在不显式指定基础类型的情况下转换为基础类型?

例子:

enum class HeapCorruptionDetectMethod {//default is int
    write_on_freed,
    buffer_underrun,
    buffer_overrun
};

auto active_method = HeapCorruptionDetectMethod::write_on_freed;

//...

//agnostic about the underlying type:
auto index = static_cast<*underlying_type*>(active_method);

也就是说,是否可以查询底层类型?

【问题讨论】:

  • 我有点好笑,因为这是字面意思第一次在 Google 上点击“underlying_type”。
  • 很抱歉挑词,但auto 并在没有明确提及的情况下获取底层类型我不会称之为“不可知论”。类型仍然存在,您不必明确提及它。 index 属于特定类型,取决于你如何使用它,它的类型会有所不同

标签: c++ enums c++17


【解决方案1】:

您可以尝试以下模板功能,我觉得它非常方便且富有表现力:

template <typename Enum>
constexpr typename std::enable_if<std::is_enum<Enum>::value, typename std::underlying_type<Enum>::type>::type
get_underlying(Enum const& value) {
    return static_cast<typename std::underlying_type<Enum>::type>(value);
}

然后你可以像这样使用它:

enum class Foo : int {
    A = 0,
    B = 1
};

int main() {
    std::cout << get_underlying(Foo::A) << std::endl; // 0
    std::cout << get_underlying(Foo::B) << std::endl; // 1

    return 0;
}

看看live

【讨论】:

  • 这个函数的目的是什么?为什么不简单地static_cast&lt;std::underlying_type&lt;Foo&gt;::type&gt;(Foo::A);
  • @idclev463035818 只是一个方便的函数,更具可读性和通用性。你不喜欢吗?
  • 坦率地说,没有。我没有看到使用它的好处。基本上你只是给已经存在的东西一个不同的名字,这反而降低了可读性。 static_caststd::underlying_type 我知道,get_underlying 我必须阅读函数才能知道它的作用
  • @idclev463035818 嗯,我想说它通过隐藏不需要知道的东西来增加可读性(即提高代码表现力)
  • 我有明确的意见,但我没有投票,因为这只是一个意见。可读性是主观的,尽管考虑到您想要做的是“转换为基础类型”,所以 static_caststd::underlying_type 都不需要知道,而是它们是准确表达这一点的标准方式
猜你喜欢
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多