Can an enum class be converted to the underlying type?

后端 未结 4 1339
不思量自难忘°
不思量自难忘° 2020-11-28 01:57

Is there a way to convert an enum class field to the underlying type? I thought this would be automatic, but apparently not.

enum class my_field         


        
4条回答
  •  孤城傲影
    2020-11-28 02:42

    I think you can use std::underlying_type to know the underlying type, and then use cast:

    #include  //for std::underlying_type
    
    typedef std::underlying_type::type utype;
    
    utype a = static_cast(my_fields::field);
    

    With this, you don't have to assume the underlying type, or you don't have to mention it in the definition of the enum class like enum class my_fields : int { .... } or so.

    You can even write a generic convert function that should be able to convert any enum class to its underlying integral type:

    template
    constexpr auto to_integral(E e) -> typename std::underlying_type::type 
    {
       return static_cast::type>(e);
    }
    

    then use it:

    auto value = to_integral(my_fields::field);
    
    auto redValue = to_integral(Color::Red);//where Color is an enum class!
    

    And since the function is declared to be constexpr, you can use it where constant expression is required:

    int a[to_integral(my_fields::field)]; //declaring an array
    
    std::array b; //better!
    

提交回复
热议问题