gpt4 book ai didi

c++ - 为什么 const 数组不能从 constexpr 函数访问?

转载 作者:太空狗 更新时间:2023-10-29 20:04:35 26 4
gpt4 key购买 nike

我有一个名为 access 的 constexpr 函数,我想访问数组中的一个元素:

char const*const foo="foo";
char const*const bar[10]={"bar"};

constexpr int access(char const* c) { return (foo == c); } // this is working
constexpr int access(char const* c) { return (bar[0] == c); } // this isn't
int access(char const* c) { return (bar[0] == c); } // this is also working

我得到错误:

error: the value of 'al' is not usable in a constant expression

为什么我不能从 access 访问其中一个元素?或者更好的是,如果可能的话,我该怎么做?

最佳答案

数组需要声明为constexpr,而不仅仅是const

constexpr char const* bar[10]={"bar"};

否则,表达式 bar[0] 会执行左值到右值的转换以取消引用数组。根据 C++11 5.19/2,第九个项目符号,这将取消它作为常量表达式的资格,除非数组是 constexpr:

an lvalue-to-rvalue conversion unless it is applied to

  • a glvalue of literal type that refers to a non-volatile object defined with constexpr

(以及一些不适用于此处的其他异常(exception)情况)。

关于c++ - 为什么 const 数组不能从 constexpr 函数访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18878427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com