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.

3
  • 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++. Commented Nov 30, 2020 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. Commented Nov 30, 2020 at 23:25
  • so you want a custom container built on top of either std::map or std::vector of pairs Commented Dec 1, 2020 at 0:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.