0

I am working with C++14 code. I have some scoped enums in which I declare a fake last element that is utilized as size in code. For example:

enum class fruits
{
    Apple = 0,
    Banana,
    Orange,

    fruitsEnd, // this is size
};

The assumption is of course that the default enum numbering is utilized. I was wondering either there is any clean way in C++14 to maybe create a constexp container like std::array instead? That would allow to use native length() and iterate over it more easily. Then I would miss the enum names however, so maybe mix the enum class with it somehow in a class/ template?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Łukasz Przeniosło
  • 2,725
  • 5
  • 38
  • 74
  • 1
    A typical approach if you want an iterable enum (which is not yet a native-language possibility) is to create a class template custom enum class which encapsules related constants which in turn have an individual ordering (and can thus be "iterated" over). This usually involves some boilerplate for the custom enum template class blueprint and a more verbose declaration and definition of each instantiation of this custom enum blueprint. See e.g. [When enum Just Isn't Enough: Enumeration Classes for C++](https://www.drdobbs.com/when-enum-just-isnt-enough-enumeration-c/184403955). – dfrib Nov 19 '19 at 11:53
  • I did something quite similar to the proposed approach. The only difference is that I am using `Qt` environment, so I was able to take advantage of the `QMetaEnum` object and encapsulate this one instead of raw scoped enum. – Łukasz Przeniosło Nov 19 '19 at 13:11
  • Possible duplicate of [Is it possible to determine the number of elements of a c++ enum class?](https://stackoverflow.com/questions/14989274/is-it-possible-to-determine-the-number-of-elements-of-a-c-enum-class) – Valeriy Savchenko Nov 22 '19 at 15:25

0 Answers0