我有一个变量声明为:
enum class FooEnum: uint64_t {}
我想转换为它的基本类型,但我不想硬编码基本类型。例如,这样的事情:
FooEnum myEnum;
uint64_t * intPointer = (underlying_typeof(myEnum))&myEnum;
这可能吗?
最佳答案
从 C++ 11 开始你可以使用这个:
-
std::underlying_type
类模板以了解枚举的基础类型。
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/