You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

指定uint8_t为底层类型的枚举,为何无法正确获取其底层类型?

明确指定底层类型的枚举,为何类型判断结果不符合预期?

你遇到的问题核心是枚举类型本身是独立的用户定义类型——哪怕你显式指定了底层类型,它也和底层类型不属于同一类型,所以std::is_same<Whatever, uint8_t>返回false是完全正常的。

至于你用std::underlying_type的测试失败,是因为用法错误:std::underlying_type是模板类,你需要访问它的::type成员来获取实际底层类型,或者用C++14引入的std::underlying_type_t(它是std::underlying_type<T>::type的别名)。

修正后的测试代码

#include <iostream>
#include <cstdint>
#include <type_traits>

enum Whatever : uint8_t
{
    first = 1,
    second
};

int main() {
    std::cout << sizeof(Whatever) << std::endl; // 输出1,符合预期
    
    // 枚举类型与底层类型是不同类型,返回false
    std::cout << (std::is_same<Whatever, uint8_t>::value ? "true" : "false") << std::endl;
    
    // C++14及以上的正确写法
    std::cout << (std::is_same_v<std::underlying_type_t<Whatever>, uint8_t> ? "true" : "false") << std::endl;
    // C++11的兼容写法
    std::cout << (std::is_same<std::underlying_type<Whatever>::type, uint8_t>::value ? "true" : "false") << std::endl;
}

运行输出

1
false
true
true

序列化场景的处理方式

对于字节缓冲区序列化需求,你只需要将枚举值显式转换为指定的底层类型即可,确保写入的类型明确:

Whatever val = Whatever::second;
uint8_t serialized_val = static_cast<uint8_t>(val);
// 此时serialized_val为明确的uint8_t类型,可直接写入缓冲区

总结:你定义的Whatever枚举的底层类型确实是uint8_t,只是枚举类型本身和底层类型属于不同的类型范畴,用std::underlying_type_t可以正确获取其底层类型。

内容的提问来源于stack exchange,提问作者Wololo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 06:03:25