为什么 constexpr 不会导致编译在索引越界时失败
Why does constexpr not cause compilation to fail on index out of bounds
我在我的 C++ 项目中编写了一个小辅助函数,它应该将 enum
的值转换为预定的字符串列表。我是这样写的:
#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));
}
我预计编译失败。我认为通过使用 constexpr
我可以在编译期间防止索引越界问题。有没有办法在 C++ 11 中强制执行此操作?
我在我的 C++ 项目中编写了一个小辅助函数,它应该将 enum
的值转换为预定的字符串列表。我是这样写的:
#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));
}
我预计编译失败。我认为通过使用 constexpr
我可以在编译期间防止索引越界问题。有没有办法在 C++ 11 中强制执行此操作?