【问题标题】:Why does constexpr not cause compilation to fail on index out of bounds为什么 constexpr 不会导致索引超出范围时编译失败
【发布时间】:2020-12-11 13:41:36
【问题描述】:

我在我的 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++打标签。这样会有更多可以回答问题的用户看到它。

标签: c++ c++11 constexpr


【解决方案1】:

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

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

这是demo


请注意,在 c++20 中,您可以创建函数 consteval,然后在所有情况下编译都会失败,因为函数必须在编译时进行评估。

这是demo

【讨论】:

    猜你喜欢
    • 2012-02-16
    • 2021-05-25
    • 2020-09-04
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多