Is it safe to reinterpret_cast an enum class variable to a reference of the underlying type?

后端 未结 3 1062
长情又很酷
长情又很酷 2020-12-03 10:59

I\'ve seen reinterpret_cast used to apply incrementation to enum classes, and I\'d like to know if this usage is acceptable in standard C++.

enu         


        
3条回答
  •  误落风尘
    2020-12-03 11:33

    The increment accesses the value of foo through an lvalue of a different type, which is undefined behaviour except in the cases listed in 3.10 [basic.lval]. Enumeration types and their underlying types are not in that list, so the code has undefined behaviour.

    With some compilers that support non-standard extensions you can do it via type-punning:

    union intenum
    {
        int8_t i;
        Foo    e;
    };
    
    intenum ie;
    for (ie.e = Foo::First; ie.e <= Foo::Last; ++ie.i)
      // ...
    

    but this is not portable either, because accessing intenum::i after storing a value in intenum::e is not allowed by the standard.

    But why not just use an integer and convert as needed?

    for (int8_t i = static_cast(Foo::First);
         i <= static_cast(Foo::Last);
         ++i)
    {
      Foo e = static_cast(i);
      // ...
    }
    

    This is portable and safe.

    (It's still not a good idea IMHO, because there could be several enumerators with the same value, or values of the enumeration type that have no corresponding enumerator label.)

提交回复
热议问题