szli
szli

Reputation: 39099

Get enum class size at compile time without defining additional element

One common approach is to add MAX as the last element, but it is not always desirable.

Any other ways? Can I do

constexpr size_t enum_size = sizeof(EnumClassName) / sizeof(std::underlying_type(EnumClassName)?

Is this safe? Not sure if I need to worry about padding. My impression is there should not be padding for enum class, because the enum item size are all the same. Assume I only use uint8_t or uint16_t as underlying type.

Upvotes: 1

Views: 3940

Answers (2)

Damon
Damon

Reputation: 70166

What you suggest does not do what you expect. Sadly, there is no support for any such thing in C++, nor is there an easy and straightforward way of doing it (numeric limits will do, but only if your enumeration values are contiguous and start at zero).

There are libraries such as Better Enums which, among other things such as name-to-string conversion, also provide determining the number of enumeration values.
They are kinda heavy though, since you need a loooooooooooot of macro abuse to implement this. On the positive side, you only pay the price in compile-time, not in binary size.

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 473537

What you're looking for (or at least, what most MAX enumerators provide) is the largest actual enumerator value. That's different from the largest possible value that the enumeration could store. The latter would be defined by std::numeric_limits<typename std::underlying_type<Enumeration>::type>::max().

There is no way to automatically get the largest enumerator value in an enumeration. Well, not automatically.

Upvotes: 1

Related Questions