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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With