3 ms·
> The reason other values of the underlying integral type beyond the named ones are allowed, is that enums are often used to specify bit values or bit masks tha
by account42 2y ago
> The reason other values of the underlying integral type beyond the named ones are allowed, is that enums are often used to specify bit values or bit masks that you AND/OR with each other. It is what it is.
Except bitwise operations of orign enum values yields the underlying type and not an enum value. And for enum classes the operators don't exist at all. So you need to write custom operators(or manual casts) for this use case anyway so you might as well go all the way and write a proper typed bitset type instead of abusing enums. Allowing this for old enums makes sense for C compat but that doesn't mean enum class couldn't have been stricter.
- gpderetta 2y ago> Except orign enum values yields the underlying type and not an enum value False: enum Foo { foo, bar }; auto x = foo|bar; static_assert(std::is_same_v<decltype(foo), Foo>); edit: I'm wrong, see below.
- account42 2y agoI meant bitwise operations of enum values and not the values themselves of course. The type of x in your example is int.
- gpderetta 2y agoAh! I meant to write decltype(x). And indeed you are right, it is int. TIL. I had checked on godblot, but of course the typo misled me. In retrospect it makes sense, there is no operator| for enum, it is just calling the int version after implicit conversion.