如何自动将强类型枚举转换为int? [英] How to automatically convert strongly typed enum into int?

查看:1282
本文介绍了如何自动将强类型枚举转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< iostream> 

struct a
{
enum LOCAL_A
{
A1,
A2
};
};
enum class b
{
B1,
B2
};

int foo(int input)
{
return input;
}

int main(void)
{
std :: cout<< foo(a :: A1)<< std :: endl;
std :: cout<< foo(static_cast< int>(b :: B2))<< std :: endl;
}

a :: LOCAL_A 是强类型枚举试图实现的,但有一个小的区别:正常枚举可以转换为整数类型,而强类型枚举不能没有转换。



那么,有没有办法将强类型枚举值转换为整数类型而不转换?如果是,如何?

解决方案

强类型枚举旨在解决多个问题,而不仅仅是你的问题中提到的范围问题:


  1. 提供类型安全,因此消除了通过整数提升的隐式转换为整数。

  2. 指定底层类型

  3. $ b

    因此,不可能隐式转换强类型枚举到整数,甚至其底层类型 - 这是想法。所以你必须使用 static_cast 来使转换明确。



    如果你唯一的问题是范围,具有隐式推广到整数,那么你最好不要使用非强类型枚举与它声明的结构的范围。



    希望它有帮助!


    #include <iostream>
    
    struct a
    {
      enum LOCAL_A
      {
        A1,
        A2
      };
    };
    enum class b
    {
        B1,
        B2
    };
    
    int foo( int input )
    {
        return input;
    }
    
    int main(void)
    {
        std::cout<<foo(a::A1)<<std::endl;
        std::cout<<foo(static_cast<int>(b::B2))<<std::endl;
    }
    

    The a::LOCAL_A is what the strongly typed enum is trying to achieve, but there is a small difference : normal enums can be converted into integer type, while strongly typed enums can not do it without a cast.

    So, is there a way to convert a strongly typed enum value into an integer type without a cast? If yes, how?

    解决方案

    Strongly typed enums aiming to solve multiple problems and not only scoping problem as you mentioned in your question:

    1. Provide type safety, thus eliminating implicit conversion to integer by integral promotion.
    2. Specify underlying types.
    3. Provide strong scoping.

    Thus, it is impossible to implicitly convert a strongly typed enum to integers, or even its underlying type - that's the idea. So you have to use static_cast to make conversion explicit.

    If your only problem is scoping and you really want to have implicit promotion to integers, then you better off using not strongly typed enum with the scope of the structure it is declared in.

    Hope it helps!

    这篇关于如何自动将强类型枚举转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆