Can an enum class be converted to the underlying type?

后端 未结 4 1346
不思量自难忘°
不思量自难忘° 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:35

    You cannot convert it implicitly, but an explicit cast is possible:

    enum class my_fields : unsigned { field = 1 };
    
    // ...
    
    unsigned x = my_fields::field; // ERROR!
    unsigned x = static_cast(my_fields::field); // OK
    

    Also mind the fact, that the semicolon should be after the closed curly brace in your enum's definition, not before.

提交回复
热议问题