我还没有找到关于 decltype 的一个很好的解释。请告诉我,作为一个初级程序员,它做了什么以及为什么有用。
例如,我正在阅读一本提出以下问题的书。有人可以向我解释答案和原因,以及一些好的(初级)示例吗?
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;
逐行解释会很有帮助。
最佳答案
decltype
是一种指定类型的方法:你给它一个表达式,decltype
给你一个对应于表达式的类型。具体来说,decltype(e)
是以下类型:
如果
e
是变量的名称,即“id-expression”,那么结果类型就是变量的类型。否则,如果
e
求值为T
类型的左值,则结果类型为T &
,如果e
计算为T
类型的右值,则结果类型为T
。
将这些规则与引用折叠规则结合起来,您可以理解 decltype(e) &&
,它始终是一个“合适的”引用。 (C++14 还添加了 decltype(auto)
给你 auto
的类型推导结合 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 & [& && collapses to &]
可能值得强调 auto
和 decltype
之间的区别:auto
适用于 types,而 decltype
适用于表达式。
您不应该在“日常”编程中看到或使用 decltype
。它在通用(模板化)库代码中最有用,其中所讨论的表达式是未知的并且取决于参数。 (相比之下,auto
可能会被广泛使用。)简而言之,如果您是编程新手,您可能不需要使用 decltype
一段时间。
关于c++ - 什么是 decltype 以及它是如何使用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18815221/