左值与文字之间的比较是否会调用左值到右值转换?
我问了这个问题:常量变量的静态声明
并且显然归结为一个问题,为了比较的目的,浮点左值是否会转换为右值?
And apparently it comes down to the question does a floating point lvalue get converted to an rvalue for the purposes of comparison?
因此在此代码中,左值到
So in this code does an lvalue-to-rvalue conversion occur?
const float foo = 13.0F;
static_assert(foo > 0.0F, "foo must be greater than 0.");
是的,它已执行。基本上是因为 3.0> 1.2
是一个格式正确的表达式,除了操作数的prvalue外,不包含其他任何内容。
Yes, it is performed. Basically, it's all because 3.0 > 1.2
is a well-formed expression, that contains nothing but prvalues for operands.
首先, [expr] / 9 指出(强调我的意思)
First, [expr]/9 states (emphasis mine) that
每当glvalue表达式作为需要该操作数的prvalue的运算符
的操作数出现时,左值到右值
数组到指针或函数到指针的标准转换是应用
来将表达式转换为prvalue。
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.
因此,问题实际上归结为关系运算符是否期望用于操作数的prvalue ?答案也是肯定的。因为我们需要考虑 [expr.rel] / 1 :
So the question really boils down to "Do the relational operators expect prvalues for operands"? And the answer to that is also yes. For we need to consider [expr.rel]/1:
relational-expression:
shift-expression
relational-expression < shift-expression
relational-expression > shift-expression
relational-expression <= shift-expression
relational-expression >= shift-expression
操作数应具有算术,枚举或指针类型。
运算符< (小于),>(大于),< =(小于或等于),
和> =(大于或等于)全部产生false或true。
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-expression
。 主要表达式
的结果之一是文字
。在 [expr.prim.literal] 中说过>:
The above grammar production is the important bit. We can follow it (I won't do it entirely here) and reduce shift-expression
to a primary-expression
. And one of the productions of a primary-expression
is a literal
. For which it is said in [expr.prim.literal]:
文字是主要表达式。其类型取决于其形式。
字符串文字是左值;所有其他文字都是prvalues。
A literal is a primary expression. Its type depends on its form. A string literal is an lvalue; all other literals are prvalues.
因为大多数文字都是prvalues,我认为可以肯定地说关系运算符 expect 运算值的prvalue。
And because most literals are prvalues, I think it's safe to say the relational operators expect prvalues for operands.