gpt4 book ai didi

c++ - 仅由变量标识符组成的表达式类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:02:44 24 4
gpt4 key购买 nike

cppreference说:

An identifier that names a variable, a function, specialization of a concept, (since C++20) or an enumerator can be used as an expression. The result of an expression consisting of just the identifier is the entity named by the identifier. [...] The type of the expression is determined as follows:

[...] Otherwise, the type of the expression is the same as the type of the entity named.

这不是一个错误吗?如果实体是引用,例如:

int &a = ...

那么a作为实体的类型是int &,而a作为表达式的类型只是int ,不是吗?表达式的类型是 never a reference :

[...] Each expression has some non-reference type

额外的问题:a 的类型(作为表达式)是 int 还是 int & 重要吗?如果是,它在哪些方面有所不同?


注意:decltype 中使用了相同的措辞:

If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, then decltype yields the type of the entity named by this expression.

但显然,decltype(a)int &

最佳答案

这是标准(草案)所说的:

[expr.type] Expressions / Type

If an expression initially has the type “reference to T”, the type is adjusted to T prior to any further analysis. ...

因此,很明显,表达式可以具有引用类型 - 最初,在类型分析调整之前。

"Each expression has some non-reference type" is not true?

取决于你如何理解它。一个表达式可以有一个非引用类型(最初),但所有表达式都有一些非引用类型(调整后)用于类型分析。

[expr.prim.id.unqual] Expressions / Unqualified names

The result is the entity denoted by the identifier. ... If the entity is a template parameter object for a template parameter of type T ... [does not apply] ... Otherwise, the type of the expression is the type of the result. [Note: The type will be adjusted as described in 7.2.2 if it is cv-qualified or is a reference type. — end note] ... [Example:

void f() {
float x, &r = x;
[=] {
decltype(x) y1; // y1 has type float
decltype((x)) y2 = y1; // y2 has type float const& because this lambda
// is not mutable and x is an lvalue
decltype(r) r1 = y1; // r1 has type float&
decltype((r)) r2 = y2; // r2 has type float const&

};
}

— end example]


Decltype specifiers [dcl.type.decltype]

... if e is an unparenthesized id-expression or ..., decltype(e) is the type of the entity named by e.

关于c++ - 仅由变量标识符组成的表达式类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56636761/

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