为什么一个const数组不能从constexpr函数访问? [英] why is a const array not accessible from a constexpr function?
问题描述
我有一个名为access的constexpr函数,我想从数组中访问一个元素:
i have a constexpr function named access, and i want to access one element from an array:
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
为什么我无法访问其中一个元素?
why can't i access one of the elements from access? or better how do i do it, if it is even possible?
推荐答案
数组需要声明 constexpr
,而不仅仅是 const
。
The array needs to be declared constexpr
, not just const
.
constexpr char const* bar[10]={"bar"};
否则,表达式 bar [0]
执行左值到右值转换,以便取消引用数组。除非数组 constexpr
,根据C ++ 11 5.19 / 2,第九个项目符号:
Without that, the expression bar[0]
performs an lvalue-to-rvalue conversion in order to dereference the array. This disqualifies it from being a constant expression, unless the array is constexpr
, according to C++11 5.19/2, ninth bullet:
一个左值到右值的转换,除非它应用到
an lvalue-to-rvalue conversion unless it is applied to
- 一个glvalue引用使用constexpr定义的非易失性对象的字面类型
在这里不适用的例外)。
(and a couple of other exceptions which don't apply here).
这篇关于为什么一个const数组不能从constexpr函数访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!