0

Say I have a

enum class foo : std::uint32_t {
    a = 4711,
    b = 815,
    ...
};

with n enumeration constants. Assume that there actual numerical value is important. I need to pass precisely one value of type T to a function for every enumeration constant in foo.

I really would like to pack them together, for example in a std::array<T, n> arr, and access the T value corresponding to the enumeration constant a by arr[a], and so on.

This would be possible, for example, if the constants would be valued by 0, 1, 2, .... Then I could write arr[static_cast<std::underlying_type_t<foo>(a)]. However, even then this is not as easy to read as arr[a].

So, is there some kind of "constexpr map or something similar? The solution I'm looking for should not be specific for foo, but quite generic, since I have multiple such foo enum classes.

0xbadf00d
  • 17,405
  • 15
  • 67
  • 107
  • 1
    There's nothing in C++ that will do it automatically. Whenever I find myself needing something that goes outside of C++ boundaries I simply use additional tools to get the job done. In this case I would hack together some scripting that defines the enumerated values externally, in some structured format, like xml or yaml, and use a script to robo-generate the `enum class` declaration and an enumerated list of all the numeric values. C++ can do everything, but not everything can be done entirely in C++. – Sam Varshavchik Nov 30 '20 at 20:25
  • You might still wrap your array in a class, and move the cast into your `operator []`. minimal perfect hashing would be ideal. Simpler, if you are in `constexpr` is simply an ordered array with all enum value. a simple find giving the corresponding index. – Jarod42 Nov 30 '20 at 23:25
  • so you want a custom container built on top of either std::map or std::vector of pairs – Sopel Dec 01 '20 at 00:51

0 Answers0