c++ - 什么是 decltype 以及它是如何使用的?

标签 c++ c++11 decltype

我还没有找到关于 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 &]

可能值得强调 autodecltype 之间的区别:auto 适用于 types,而 decltype 适用于表达式

您不应该在“日常”编程中看到或使用 decltype。它在通用(模板化)库代码中最有用,其中所讨论的表达式是未知的并且取决于参数。 (相比之下,auto 可能会被广泛使用。)简而言之,如果您是编程新手,您可能不需要使用 decltype一段时间。

关于c++ - 什么是 decltype 以及它是如何使用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18815221/

相关文章:

c++ - 优化 C++11 随机生成器的使用

c++ - 英特尔 SSE 的斜坡函数

c++ - 为什么这个简单的 lambda 在 std::thread 中始终比在 gcc 4.9.2 的 main 函数中运行得更快?

C++ - 将 decltype 与包含在模板类中的枚举一起使用

c++ - 为什么在 C++11 中需要 decltype?

html - 将字符串中的 č、š、ć 等字符替换为其 html 代码 C++

c++ - 任意维数组

json - 如何使用 Poco C++ 创建和解析分层/嵌套 JSON?

c++ - 在 `std::get<I>` 上使用 `std::tuple` 是否保证对于 `I` 的不同值是线程安全的?

c++ - C2228使用decltype时出错