gpt4 book ai didi

c++11 - 为什么 decltype 的行为是这样定义的?

转载 作者:行者123 更新时间:2023-12-04 17:19:12 25 4
gpt4 key购买 nike

来自 C++ 草案标准 N3337:

7.1.6.2 Simple type specifiers

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

— if e is an unparenthesized id-expression or an unparenthesized 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 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;


如果我正确理解上述内容,
int a;
decltype(a) b = 10; // type of b is int

int* ap;
decltype(*ap) c = 10; // Does not work since type of c is int&
你能解释一下,或者指出一些解释为什么 decltype(*ap) 的文档吗?不可能只是 int ?

最佳答案

decltype的标准化努​​力这是一项跨越多年的艰巨努力。在委员会最终接受之前,这篇论文有 7 个版本。版本是:

  • N1478 2003-04-28
  • N1527 2003-09-21
  • N1607 2004-02-17
  • N1705 2004-09-12
  • N1978 2006-04-24
  • N2115 2006-11-05
  • N2343 2007-07-18

  • 值得注意的是,您质疑的行为的种子在第一次修订中: N1478 ,这引入了“两种类型的 typeof:保留或删除类型中的引用”的需要。

    本文继续给出了引用保留变体的基本原理,包括以下引用:

    On the other hand, the reference-dropping semantics fails to provide a mechanism for exactly expressing the return types of generic functions, as demonstrated by Strous- trup [Str02]. This implies that a reference-dropping typeof would cause problems for writers of generic libraries.



    阅读这些论文是无可替代的。然而,可以总结为 decltype有两个目的:
  • 报告标识符的声明类型。
  • 报告表达式的类型。

  • 对于第二个用例,请记住表达式从不是引用类型,而是左值、x 值或纯右值之一。按照惯例,当 decltype报告左值表达式的类型,它使该类型成为左值引用,当表达式是 xvalue 时,报告的类型成为右值引用。

    在您的示例中, *ap是一个表达式,而 a是一个标识符。因此,您的示例同时使用了这两个用例,如 N1478 中首次介绍的那样.

    还需要注意的是 decltype不是孤立设计的。 C++ 语言的其余部分在此期间不断发展(例如右值引用),以及 decltype 的设计被迭代以跟上步伐。

    另请注意,一旦 decltype提案被接受,它继续(并持续到今天)发展。请参阅此问题列表:

    http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_index.html

    特别是第 7.1.6.2 节(这是大部分 decltype 规范所在的部分)。

    关于c++11 - 为什么 decltype 的行为是这样定义的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26088799/

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