C++0x : conditional operator, x值和decltype

标签 c++ c++11 rvalue-reference defects

我正在重新发布 comp.std.c++ Usenet discussion在这里是因为那个小组变得非常不可靠。我在那里提交的最后几篇帖子都变成了空白,事件几乎停止了。我怀疑我是否被禁止和/或其他人只是失去了兴趣。希望所有感兴趣的人都能找到这个讨论,并且会有一个普遍的迁移。也许那时他们会任命一位新的主持人。


您好!

根据我目前对 N3126 草案的解释 w.r.t.有条件的 运算符和 xvalues,我希望以下断言成立:

 int i = 0;
 int& j = true? i : i;
 int&& k = true? std::move(i) : std::move(i);   // #2
 assert(&i == &j); // Holds since C++98
 assert(&i == &k); // Should this hold as well?

5.16/4 说:

If the second and third operands [to the conditional operator] are glvalues of the same value category and have the same type, the result is of that type and value category [...]

不过,它并没有明确说明生成的泛左值是指 glvalue 操作数引用的对象之一——或者是这个 暗示因为否则它会返回一个纯右值?使用 GCC 4.5.1 在 C++0x 模式下,第二个断言失败。引用 k 似乎 引用一些临时对象。有人可以澄清是否 允许编译器创建这样的临时文件,以防两个操作数 冒号周围是相同类型的 xvalues?

我目前假设 GCC 有问题和/或不是最新的 到 xvalues。

后续问题是:如果能够检测到 表达式的值类别?如果我们忽略条件运算符 我们可以使用 decltype 检测表达式的值类别。但 什么是

 bool xvalue = std::is_rvalue_reference<
   decltype( true ? std::move(i) : std::move(i) ) >::value;

应该屈服?使用 GCC 4.5.1,初始化 xvalue 变量 与假。这是否符合当前的标准草案?

TIA, 塞巴斯蒂安

最佳答案

我认为 GCC 4.5.1 不符合 §5.16/4。你有没有filed a bug report

无论如何,我认为它符合那个三元运算符代码。 decltype 由 §7.1.6.2/4 定义:

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

  • if e is an unparenthesized id-expression or a class member access (5.2.5), 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 a function call (5.2.2) or an invocation of an overloaded operator (parentheses around e are ignored), decltype(e) is the return type of the statically chosen function;
  • 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 (Clause 5).

decltype 通过获取适当的声明并从中返回所需的类型来工作。对于非重载运算符,它几乎没有智能。或许还有一点

  • 否则,如果 e 是一个 xvalue,则 decltype(e) 是 T&&,其中 Te< 的类型

将是有序的,特别是因为如所写,xvalues 被视为 prvalues。此外,您的表达式完全对应于 std::common_type (§20.7.6.6/3) 的定义。

一个简单的解决方法(创造一个短语 :vP ):

template< typename T1, typename T2 >
struct common_type_and_category {
    typedef typename std::conditional<
        std::is_same< T1, T2 >::value,
        T1,
        typename std::common_type< T1, T2 >::type
    >::type type;
};

关于C++0x : conditional operator, x值和decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3909720/

相关文章:

适用于 Windows 和 Linux 的 c++ xml、tcp/ip 库

c++ - 如何加快我的稀疏矩阵求解器?

c++ - std::initializer_list 不允许缩小

c++ - auto-complete-clang-async 无法按预期在 Emacs 上运行

c++ - 如何 move std::ostringstream 的底层字符串对象?

C++:我的右值在哪里?

c++ - 模板函数重载

c++ - 是否可以在未推导所有模板参数的情况下获取模板成员函数的函数指针?

c++ - 中断点和清理退出

c++ - 在 C++11 的模板化函数中处理 void 变量