gpt4 book ai didi

c++ - 条件表达式中的右值引用

转载 作者:太空狗 更新时间:2023-10-29 20:45:37 28 4
gpt4 key购买 nike

typedef decltype(true ? (long&&)0 : (long&&)0) T;

T 应该是什么?

根据 gcc (4.7),它是 long。根据 clang (trunk),它是 long&&。这种差异导致 clang 无法编译使用 gcc 4.7 的 libstdc++ 的代码。谁是对的?

更新:正如ildjarn 指出的那样,Clang 是正确的,并且正如Richard Smith 指出的那样,错误libstdc++ 是由于一个错误在标准中。这是 relevant GCC bug , 和 relevant Defect Report .

最佳答案

Clang 是对的。 N3337 §7.1.6.2/4:

The type denoted by decltype(e) is defined as follows:

  • if e is an unparenthesized id-expression or an unparenthesized class member access, 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 functions, 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.

The operand of the decltype specifier is an unevaluated operand.

§5/6:

[ Note: An expression is an xvalue if it is:

  • the result of calling a function, whether implicitly or explicitly, whose return type is an rvalue reference to object type,
  • a cast to an rvalue reference to object type,
  • a class member access expression designating a non-static data member of non-reference type in which the object expression is an xvalue, or
  • a .* pointer-to-member expression in which the first operand is an xvalue and the second operand is a pointer to data member.

In general, the effect of this rule is that named rvalue references are treated as lvalues and unnamed rvalue references to objects are treated as xvalues; rvalue references to functions are treated as lvalues whether named or not. —end note ]

我之前很小心,文字 0 可能会以某种方式阻止它在这种情况下成为对象类型,但 §3.9/8 澄清了一些事情:

An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.

条件运算符不会影响此处的任何内容 – §5.16/4:

If the second and third operands are glvalues of the same value category and have the same type, the result is of that type and value category and it is a bit-field if the second or the third operand is a bit-field, or if both are bit-fields.

在这种情况下,两者属于相同的值类别 (xvalue),并且 xvalues 是 glvalues。

关于c++ - 条件表达式中的右值引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10359590/

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