gpt4 book ai didi

c++ - 为什么字符串文字上的 decltype 不产生数组类型?

转载 作者:可可西里 更新时间:2023-11-01 15:38:11 26 4
gpt4 key购买 nike

该标准在 §2.13.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 (3.7).

因此,例如,"sss" 应该有一个类型 char const[4](除非我没看错)。

但是这个简单的片段:

std::cout << std::boolalpha << std::is_pointer<decltype("sss")>::value << '\n';
std::cout << std::boolalpha << std::is_array<decltype("sss")>::value;

gives :

false
false

我错过了什么?

最佳答案

字符串文字是左值([expr.prim.general]/p1):

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.

decltype(expr) 当表达式 expr 是左值表达式 ([dcl.type.simple]/p4) 时返回左值引用:

For an expression e, the type denoted by decltype(e) is defined as follows:

  • 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]

简单地删除引用应该会给你你想要的行为:

std::is_array<std::remove_reference_t<decltype("sss")>>::value;

关于c++ - 为什么字符串文字上的 decltype 不产生数组类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293262/

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