gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:44:52 25 4
gpt4 key购买 nike

我有一个变量声明为:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com