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
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.)