gpt4 book ai didi

c++ - 左值和文字之间的比较是否会引发左值到右值的转换?

转载 作者:太空狗 更新时间:2023-10-29 21:34:20 26 4
gpt4 key购买 nike

我问了这个问题:static_assert of const Variable

显然,问题归结为浮点左值是否为了比较目的转换为右值?

那么在这段代码中是否发生了左值到右值的转换?

const float foo = 13.0F;
static_assert(foo > 0.0F, "foo must be greater than 0.");

最佳答案

是的,它被执行了。基本上,这都是因为 3.0 > 1.2 是一个格式正确的表达式,它只包含操作数的纯右值。

首先,[expr]/9声明(强调我的)

Whenever a glvalue expression appears as an operand of an operator that expects a prvalue for that operand, the lvalue-to-rvalue, array-to-pointer, or function-to-pointer standard conversions are applied to convert the expression to a prvalue.

所以问题真的可以归结为“关系运算符是否期望操作数的纯右值”?答案也是肯定的。因为我们需要考虑[expr.rel]/1 :

relational-expression:
shift-expression
relational-expression < shift-expression
relational-expression > shift-expression
relational-expression <= shift-expression
relational-expression >= shift-expression

The operands shall have arithmetic, enumeration, or pointer type. The operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) all yield false or true. The type of the result is bool.

上面的语法生成是重要的一点。我们可以遵循它(我不会在这里完全这样做)并将 shift-expression 简化为 primary-expressionprimary-expression 的产生式之一是 literal[expr.prim.literal] 中对此进行了说明:

A literal is a primary expression. Its type depends on its form. A string literal is an lvalue; all other literals are prvalues.

而且因为大多数文字都是纯右值,我认为可以肯定地说关系运算符期望操作数的纯右值。

关于c++ - 左值和文字之间的比较是否会引发左值到右值的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46980595/

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