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

显式指定类型的枚举为何使std::is_same_v返回false?

问题分析与解决

哈哈,这个问题我刚学C++的时候也踩过!你忽略了std::underlying_type的本质——它不是直接返回底层类型的别名,而是一个类型特性模板,得通过它的内部成员或者便捷别名才能拿到真正的底层类型。

问题根源

你原来的代码里,std::underlying_type<Color>是std::underlying_type模板针对Color的实例化类型(一个类型特性对象),而int是基础数据类型,这两者完全不是同一类东西,所以std::is_same_v自然会返回false。

修正方案

有两种写法可以得到正确结果:

写法1:使用C++14引入的便捷别名 std::underlying_type_t

这个别名直接等价于typename std::underlying_type<T>::type,用起来更简洁:

#include <iostream>
#include <type_traits>
enum class Color: int { Red, Blue };
int main() {
    constexpr bool match = std::is_same_v<std::underlying_type_t<Color>, int>;
    std::cout << std::boolalpha << match << std::endl; // 现在会输出true
}

写法2:显式访问std::underlying_type的type成员

如果你需要兼容C++11,可以手动指定typename来访问内部的type成员:

#include <iostream>
#include <type_traits>
enum class Color: int { Red, Blue };
int main() {
    constexpr bool match = std::is_same_v<typename std::underlying_type<Color>::type, int>;
    std::cout << std::boolalpha << match << std::endl; // 同样输出true
}

补充说明

std::underlying_type的设计是为了遵循C类型特性的统一范式——所有类型特性模板都通过内部的type成员暴露目标类型,而C14及以后的_t后缀别名就是为了简化这种写法,减少冗余代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:07:20