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

标签 c++ c++11

我有一个变量声明为:

enum class FooEnum: uint64_t {}

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

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

这可能吗?

最佳答案

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

doc说,

Defines a member typedef type of type that is the underlying type for the enumeration 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) 即可获得值(value):

auto value = std::to_underlying<FooEnum>(myEnum);

关于c++ - 如何知道类枚举的基础类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9343329/

相关文章:

c++ - C++11 将改变哪些良好的编程实践?

c++ - 将可变参数模板类型转换为 void,预期为 ')' 之前

C++ cmath pow 错误存在于旧版本的编译器中,但不存在于新版本中

c++ - 如何连接二进制宏值?什么是二进制类型?

c++ - 关键字 `this` 可以在类范围内使用吗?

c++ - 在 C++ 中从 unsigned long long 到 unsigned int 的转换

C++ 指向类和析构类的指针

c++ - 通过引用传递数组

c++ - 自动参数捕获的推导规则是什么?

c++ - 比较 reference_wrappers 的地址