why is a const array not accessible from a constexpr function?

拥有回忆 提交于 2019-12-20 01:58:09

问题


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

i get the error:

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?


回答1:


The array needs to be declared constexpr, not just const.

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

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

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

(and a couple of other exceptions which don't apply here).



来源:https://stackoverflow.com/questions/18878427/why-is-a-const-array-not-accessible-from-a-constexpr-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!