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

标签 c++ comparison rvalue lvalue lvalue-to-rvalue

我问了这个问题: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/

相关文章:

c++ - 通过引用识别 Lambda

c++ - 无符号到有符号的转换

javascript - 在 JavaScript 中创建 deepEqual 函数

c++ - 返回右值或左值

c++ - 试图将地址传递给对指针的引用

c++ - c++ 中的右值如何存储在内存中?

c# - 如何在二进制文件(.net 或非托管)中注入(inject)/更新版本和其他详细信息?

c++ - std::为无序集(或映射)插入迭代器?

javascript - 比较两个对象数组 JS

c++ - 比较 vector 的 vector