2.auto、decltype和decltype(auto)的用法

2.auto、decltype和decltype(auto)的用法

这三个都是 C++11 及以后的类型推导关键字,我给你用最清晰、面试能直接说的版本讲一遍。

2.1 auto

  • 作用从表达式的值推导变量类型
  • 推导规则:
    • 自动忽略顶层 const、引用
    • 会发生类型退化(数组→指针,函数→指针)
int x = 10;
auto a = x;        // int

const int& rx = x;
auto b = rx;       // int(& 和 const 被丢掉)

int arr[5];
auto c = arr;      // int*
  • 常见用途:简化迭代器、简化复杂类型、范围 for
for (auto& item : vec) { ... }

2.2 decltype(expr)

  • 作用精确提取表达式的 “声明类型”
  • 不会丢掉 const & 引用,不会退化
  • 只分析类型,不计算表达式
int x = 10;
const int& rx = x;

decltype(x)  a;    // int
decltype(rx) b;    // const int&(完全一致)
decltype(x + 1) c; // int
  • 常用于:返回值类型、模板元、精确保留引用

2.3 decltype(auto)(C++14)

  • 作用:用 auto占位,但推导规则完全按 decltype 来
  • 即:
    • 既像 auto 一样自动推导
    • 又像 decltype 一样完整保留引用、const

主要用在两个地方:

(1) 变量定义

int x = 10;
const int& rx = x;

decltype(auto) a = rx;  // const int&

(2) 函数返回值推导(最常用)

想要完美转发返回值(原值是引用就返回引用,是值就返回值):

decltype(auto) func() {
    return some_expr;
}

一句话对比总结

  • auto:推导值类型,丢引用、丢顶层 const,会退化
  • decltype(expr)原样提取表达式类型,不丢引用 /const
  • decltype(auto):用 auto 推导,但规则同 decltype,用于完美转发返回值 / 精确推导变量
posted @ 2023-08-02 22:04  CodeMagicianT  阅读(512)  评论(0)    收藏  举报