为什么字符串文字上的 decltype 不会产生数组类型? [英] Why does decltype on a string literal not yield an array type?

查看:22
本文介绍了为什么字符串文字上的 decltype 不会产生数组类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准在 §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).

但是这个简单的片段:

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).字符串文字是左值;所有其他文字都是纯右值.

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 是 xvalue,则 decltype(e) 是 T&&,其中 T 是 e 的类型;
  • 否则,如果 e 是左值,则 decltype(e) 是 T&,其中 T 是 e 的类型;
  • 否则,decltype(e) 是 e 的类型.

字符串文字 N const char 的数组,但你所经历的是decltype的效果.你真正拥有的是 char const(&)[N], not 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆