为什么字符串文字上的decltype不产生数组类型? [英] Why does decltype on a string literal not yield an array type?
问题描述
该标准在§2.13.5/8中将字符串文字的类型定义为:
The standard defines a string literal's type, in §2.13.5/8, as:
普通字符串文字和UTF-8字符串文字也称为窄字符串文字.窄字符串文字的类型为"n const char数组",其中n是如下定义的字符串的大小,并且具有静态存储持续时间(3.7).
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 (3.7).
因此,例如,"sss"
应该具有类型char const[4]
(除非我读错了它).
Therefore, for example, "sss"
should have a type char const[4]
(unless I'm reading it incorrectly).
但是这个简单的代码段:
But this simple snippet:
std::cout << std::boolalpha << std::is_pointer<decltype("sss")>::value << '\n';
std::cout << std::boolalpha << std::is_array<decltype("sss")>::value;
给予:
false
false
我想念什么?
推荐答案
字符串文字是左值([expr.prim.general]/p1):
String literals are lvalues ([expr.prim.general]/p1):
文字是主要表达式.其类型取决于其形式(2.13).字符串文字是左值;所有其他文字都是prvalue.
A literal is a primary expression. Its type depends on its form (2.13). A string literal is an lvalue; all other literals are prvalues.
当表达式expr
是左值表达式([dcl.type.simple]/p4)时,
decltype(expr)
返回左值引用:
decltype(expr)
returns an lvalue-reference when the expression expr
is an lvalue expression ([dcl.type.simple]/p4):
对于表达式e,由decltype(e)表示的类型定义为 如下:
For an expression e, the type denoted by decltype(e) is defined as follows:
- 如果e是未括号化的id表达式或未括号化的类成员访问权限(5.2.5),则decltype(e)是实体的类型 由e命名.如果没有这样的实体,或者e命名一组 重载的功能,程序格式不正确;
- 否则,如果e是x值,则decltype(e)是T&& ;,其中T是e;的类型.
- 否则,如果e为左值,则decltype(e)为T& ;,其中T为e的类型;
- 否则,decltype(e)是e的类型.
- if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e) is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded func- tions, the program is ill-formed;
- otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
- otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
- otherwise, decltype(e) is the type of e.
字符串文字是N
const char
的数组,但是您遇到的是decltype
的作用.您真正拥有的是类型char const(&)[N]
,不是 char const[N]
.
String literals are arrays of N
const char
, but what you are experiencing is the effect of decltype
. What you really have is the type char const(&)[N]
, not char const[N]
.
只需删除引用,即可获得所需的行为:
Simply removing the reference should give you the behavior you desire:
std::is_array<std::remove_reference_t<decltype("sss")>>::value;
这篇关于为什么字符串文字上的decltype不产生数组类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!