Possible Duplicate:
Can a string literal be subscripted in a constant expression?
如果我为字符串文字添加下标,结果是编译时常量吗?换句话说,下面的代码有效吗?
constexpr char x = "a"[0];
GCC 4.7 是这么说的,但标准对此有何规定?
对于好奇的人:我不能只写 'a'
,因为字符串文字是字符串化运算符的结果。有些编译器确实有一个 charizing 运算符,但它只是一个扩展。
最佳答案
我认为您正在查看 5.19 [expr.const]:
2 - A conditional-expression is a core constant expression unless it involves one of the following [...]
- an lvalue-to-rvalue conversion (4.1) unless it is applied to
- a non-volatile glvalue of integral or enumeration type that refers to a non-volatile const object with a preceding initialization, initialized with a constant expression [ Note: a string literal (2.14.5) corresponds to an array of such objects. —end note ] [...]
因此字符串文字下标运算的结果可能会转换为核心常量表达式中的右值。
在为用户定义的文字和用户定义的字符串文字定义 constexpr 运算符时,这很有用,尽管可变参数形式在某些情况下更可行。
关于c++ - 在编译时常量中为字符串文字添加下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12530408/