如何知道类枚举的基础类型?

2024-05-07

我有一个变量声明为:

enum class FooEnum: uint64_t {}

我想转换为它的基本类型,但我不想对基本类型进行硬编码。例如,这样的事情:

FooEnum myEnum;
uint64_t * intPointer = (underlying_typeof(myEnum))&myEnum;

这可能吗?


从 C++ 11 开始你可以使用这个:

  • std::underlying_type http://en.cppreference.com/w/cpp/types/underlying_type类模板来了解枚举的基础类型。

The doc http://en.cppreference.com/w/cpp/types/underlying_type says,

定义一个成员typedef类型type这是枚举 T 的基础类型。

所以你应该能够这样做:

#include <type_traits> //include this

FooEnum myEnum;
auto pointer = static_cast<std::underlying_type<FooEnum>::type*>(&myEnum);

在 C++ 14 中它已经有点简化了(注意没有::type):

auto pointer = static_cast<std::underlying_type_t<FooEnum>*>(&myEnum);

最后从 C++ 23 开始无需显式转换即可获取值(docs https://en.cppreference.com/w/cpp/utility/to_underlying):

auto value = std::to_underlying<FooEnum>(myEnum);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何知道类枚举的基础类型? 的相关文章