Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ensure that each case defined in an enum class is treated, e.g. using static_assert?

Tags:

c++

enums

c++11

Assume an enum class

enum class MY_ENUM {FOO, BAR};

and a std::map which holds some information about each element in the enum

map<MY_ENUM, MyInfoType> enumInfos;

How can I ensure at compile time that for each value of the enum there is an entry in the map?

I would like to be able to write something like (of course this code is not valid):

for (auto& elem : MY_ENUM) {
    static_assert(enumInfos.find(elem) != enumInfos.end(),
        "Error: Information for an element in MY_ENUM is missing.")
}

Is something like this possible?

like image 392
user2296653 Avatar asked Dec 02 '25 23:12

user2296653


1 Answers

Short answer: no, it is not possible. That's because a std::map cannot be built at compile time: it doesn't have a constexpr constructor, and has a non-trivial destructor.

As to why map is a challenge to implement in a constexpr manner, it is probably because it uses dynamic memory allocation by its default allocator. If somehow will be possible to construct a compile-time allocator (which may be, in C++ never say never), then it may be possible to have a constexpr map.

like image 172
vsoftco Avatar answered Dec 04 '25 11:12

vsoftco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!