use*_*087 3 c++ constexpr c++11
我有一个名为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
Run Code Online (Sandbox Code Playgroud)
我收到错误:
error: the value of 'al' is not usable in a constant expression
Run Code Online (Sandbox Code Playgroud)
为什么我不能从访问中访问其中一个元素?或者更好我该怎么做,如果有可能的话?
需要声明数组constexpr
,而不仅仅是声明const
.
constexpr char const* bar[10]={"bar"};
Run Code Online (Sandbox Code Playgroud)
如果没有这个,表达式将bar[0]
执行左值到右值的转换,以便取消引用数组.这取消了它作为常量表达式的资格,除非数组是constexpr
,根据C++ 11 5.19/2,第九个子弹:
除非适用,否则左值转换为左值
- 文字类型的glvalue,指的是用constexpr定义的非易失性对象
(以及其他一些不适用的例外情况).
归档时间: |
|
查看次数: |
605 次 |
最近记录: |