为什么 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 中强制执行此操作?

是的,但是您在 运行 时间调用了该函数。如果您在编译时上下文中调用此函数,例如通过分配给一个 constexpr 变量,你会得到一个编译时错误:

constexpr auto c = get_thing_string(static_cast<things>(12));  // error

这里是 demo


请注意,在 c++20 中,您可以创建函数 consteval,然后在所有情况下编译都会失败,因为函数 必须 在编译时求值时间.

这里是 demo