marcbf
marcbf

Reputation: 317

Programmatically deduce the size of an enum independently of the value of its elements?

Is there any way, possibly requiring C++11/14, to deduce the number of elements in an enum regardless of the values of the enum elements themselves?

Consider an enum like

enum { Val1 = 1, Val2 = 2, Val3 = 4 }

for which the answer would be 3. I know there's that wrinkle, where I could have e.g. Val3 = Val1, but this can be ignored for my use case.

I've seen quite a few similar questions, both here on SO and elsewhere, but I've yet to find a proper answer for this. If there is any at all.

Usually, the proposed solution is to introduce a LAST element, but this would only give me the next higher enum value (using the example above, that would be 5), which would be of no use to me.

Upvotes: 4

Views: 234

Answers (1)

gsamaras
gsamaras

Reputation: 73376

If there is any at all.

There is not.

Even with the new C++17, there is not a proposal that I am aware of that would allow you to achieve this.

Usually, the proposed solution is to introduce a LAST element, but this would only give me the next higher enum value (using the example above, that would be 5), which would be of no use to me.

Then you will have to re-aproach your problem.

Upvotes: 2

Related Questions