gpt4 book ai didi

c++ - 字符串文字可以在常量表达式中下标吗?

转载 作者:IT老高 更新时间:2023-10-28 22:15:05 25 4
gpt4 key购买 nike

这是有效的,因为 constexpr 表达式允许采用“一个字面量类型的左值,它引用一个用 constexpr 定义的非 volatile 对象,或者引用一个子-此类对象的对象”(§5.19/2):

constexpr char str[] = "hello, world";
constexpr char e = str[1];

但是,字符串文字似乎不符合此描述:

constexpr char e = "hello, world"[1]; // error: literal is not constexpr

2.14.5/8 描述了字符串字面量的类型:

Ordinary string literals and UTF-8 string literals are also referred to as narrow string literals. A narrow string literal has type “array of n const char”, where n is the size of the string as defined below, and has static storage duration.

这种类型的对象似乎可以被索引,只要它是临时的而不是静态存储持续时间(5.19/2,就在上面的片段之后):

[constexpr allows lvalue-to-rvalue conversion of] … a glvalue of literal type that refers to a non-volatile temporary object whose lifetime has not ended, initialized with a constant expression

这特别奇怪,因为获取临时对象的左值通常是“作弊”。我想这条规则适用于引用类型的函数参数,例如在

constexpr char get_1( char const (&str)[ 6 ] )
{ return str[ 1 ]; }

constexpr char i = get_1( { 'y', 'i', 'k', 'e', 's', '\0' } ); // OK
constexpr char e = get_1( "hello" ); // error: string literal not temporary

不管怎样,GCC 4.7 接受 get_1( "hello"),但拒绝 "hello"[1] 因为“'._0' 的值是不能在常量表达式中使用”……但 “hello”[1] 可以作为案例标签或数组绑定(bind)。

我在这里 split 了一些标准的头发......分析是否正确,这个功能是否有一些设计意图?

编辑:哦……这有一些动机。似乎这种表达式是在预处理器中使用查找表的唯一方法。例如,这会引入一个代码块,除非 SOME_INTEGER_FLAG 为 1 或 5,否则该代码块会被忽略,如果大于 6,则会导致诊断:

#if "\0\1\0\0\0\1"[ SOME_INTEGER_FLAG ]

这个结构对于 C++11 来说是新的。

最佳答案

这样做的目的是,说明左值到右值转换何时有效的段落将 be amended with a note表示引用字符串字面量子对象的左值是一个常量整数对象,在 C++11 后的草案中使用常量表达式(被描述为允许的情况之一)初始化。

您对预处理器中使用的评论看起来很有趣,但我不确定这是否有用。这是我第一次听说。

关于c++ - 字符串文字可以在常量表达式中下标吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7424647/

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