I wrote a small helper function in my c++ project which should convert values of an enum to a predetermined list of strings. I wrote it like this:
#include <stdint.h>
#include <iostream>
enum things{
val1 = 0,
val2,
val3,
val4
};
constexpr const char* things_strings[4] = {"A", "B", "C", "D"};
constexpr const char* get_thing_string(const things thing){
return things_strings[static_cast<uint32_t>(thing)];
}
int main(){
std::cout << get_thing_string(things::val1);
std::cout << get_thing_string(static_cast<things>(12));
}
I expected this to fail compilation. I thought that by using constexpr I can prevent index out of bounds issues during compile time. Is there a way to enforce this in C++ 11?
Aucun commentaire:
Enregistrer un commentaire