underlying_type

#include <iostream>
#include <type_traits>

enum e1 {};
enum class e2 {};
enum class e3: unsigned {};
enum class e4: int {};

int main() {

  constexpr bool e1_t = std::is_same< std::underlying_type<e1>::type, int >::value;
  constexpr bool e2_t = std::is_same< std::underlying_type<e2>::type, int >::value;
  constexpr bool e3_t = std::is_same< std::underlying_type<e3>::type, int >::value;
  constexpr bool e4_t = std::is_same< std::underlying_type<e4>::type, int >::value;

  std::cout
    << "underlying type for 'e1' is " << (e1_t ? "int" : "non-int") << '\n'
    << "underlying type for 'e2' is " << (e2_t ? "int" : "non-int") << '\n'
    << "underlying type for 'e3' is " << (e3_t ? "int" : "non-int") << '\n'
    << "underlying type for 'e4' is " << (e4_t ? "int" : "non-int") << '\n'
    ;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"Implicit conversion of underlying type" 是一个编译器警告,通常出现在程序中使用枚举类型时。这个警告的含义是,程序在使用枚举类型时,可能会出现隐式转换的情况,从而导致错误的结果。 枚举类型是一种特殊的数据类型,它可以将一组常量绑定在一起,并使用有意义的标识符来引用这些常量。在一些编程语言中,枚举类型可以使用整型或其他基本数据类型来表示枚举常量。在这种情况下,如果我们使用枚举类型的值进行运算或比较,编译器可能会尝试将枚举类型的值隐式转换为其底层数据类型。 例如,在C++中,我们可以定义以下枚举类型: ```c++ enum Color { Red = 1, Green = 2, Blue = 3 }; ``` 在这个例子中,枚举类型Color使用整型来表示枚举常量。如果我们使用枚举类型的值进行运算或比较,编译器可能会尝试将枚举类型的值隐式转换为整型,从而导致错误的结果。 为了避免这个问题,我们可以显式地将枚举类型的值转换为其底层数据类型,或者使用枚举类型的名称来引用枚举常量。例如,在上面的例子中,我们可以使用以下代码来避免这个问题: ```c++ Color c = Green; int value = static_cast<int>(c); // 显式转换为整型 if (c == Color::Green) { // 使用枚举类型的名称来引用枚举常量 // ... } ``` 在这个例子中,我们使用static_cast操作符来将枚举类型的值显式转换为整型,或者使用枚举类型的名称来引用枚举常量,从而避免了隐式转换可能导致的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值