什么是decltype,它是如何使用的? [英] What is decltype and how is it used?

查看:1010
本文介绍了什么是decltype,它是如何使用的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有找到一个很好的解释decltype。请告诉我,作为一个开始的程序员,它是什么,为什么它是有用的。

I haven't been able to find a good explanation of decltype. Please tell me, as a beginning programmer, what it does and why it is useful.

例如,我正在读一本书,问了以下问题。有人可以向我解释一下答案,以及为什么,以及一些好的(初级水平)示例?

For example, I am reading a book that asked the following question. Can someone explain to me the answer and why, along with some good (beginner-level) examples?


变量和每个变量在代码结束时有什么值?

What would be the type of each variable and what value would each variable have when the code finishes?

int a = 3, b = 4;    
decltype(a) c = a;

decltype((b)) d = a; 

++c; 

++d;


逐行解释会非常有帮助。 / p>

A line-by-line explanation would be very helpful.

推荐答案

decltype 是一种指定类型的方法: decltype 会返回一个对应于表达式类型的类型。具体来说, decltype(e)是以下类型:

decltype is a way to specify a type: You give it an expression, and decltype gives you back a type which corresponds to the type of the expression. Specifically, decltype(e) is the following type:


  • e 是变量的名称,即id-expression,则结果类型是变量的类型。

  • If e is the name of a variable, i.e. an "id-expression", then the resulting type is the type of the variable.

否则,如果 e 计算为类型 T 的左值,是 T& ,并且如果 e 评估类型 T ,则结果类型为 T

Otherwise, if e evaluates to an lvalue of type T, then the resulting type is T &, and if e evaluates to an rvalue of type T, then the resulting type is T.

将这些规则与参考折叠规则相结合,可以使你理解 decltype(e)&& ,它总是一个合适的引用。 (C ++ 14还添加 decltype(auto),以给出类型扣除 auto decltype 的类别语义。)

Combining these rules with reference collapsing rules allows you to make sense of decltype(e) &&, which is always a "suitable" reference. (C++14 also adds decltype(auto) to give you the type-deduction of auto combined with the value category semantics of decltype.)

示例:

int foo();
int n = 10;

decltype(n) a = 20;             // a is an "int" [id-expression]

decltype((n)) b = a;            // b is an "int &" [(n) is an lvalue]

decltype(foo()) c = foo();      // c is an "int" [rvalue]

decltype(foo()) && r1 = foo();  // int &&
decltype((n)) && r2 = n;        // int &

可能值得强调 auto decltype auto 适用于类型

It might be worth stressing the difference between auto and decltype: auto works on types, and decltype works on expressions.

您不应该看到或使用 decltype code>在日常编程中。它在泛型(模板)库代码中最有用,其中有问题的表达式是未知的,并且取决于参数。 (相比之下, auto 可以在整个地方使用。)总之,如果你刚开始编程,你可能不需要使用 decltype 一段时间。

You shouldn't be seeing or using decltype in "day-to-day" programming. It is most useful in generic (templated) library code, where the expression in question is not known and depends on a paramater. (By contrast, auto may be used generously all over the place.) In short, if you're new to programming, you probably won't need to use decltype for some time.

这篇关于什么是decltype,它是如何使用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆