1.auto VS decltype

  • auto 是根据变量初始值推导类型;decltype 是根据表达式推导类型。
auto a = 10; // int a
decltype(10) b; //从表达式推导类型,不计算表达式,只分析表达式的类型

2. auto

语法:auto 变量 = 表达式;

  • 必须初始化
  • 自动丢弃顶层 const、引用
  • 适合定义变量、迭代器、遍历
const int x = 10;
int& rx = x;
auto a = x;   // int (丢失 const)
auto b = rx;  // int (丢失引用)

3. decltype

语法:decltype(表达式) 变量;

decltype(10)    a;   // int
decltype(3.14)  b;   // double
decltype(true)  c;   // bool
const int val = 100;
auto         x = val;   // int
decltype(val) y = val;  // const int
int num = 10;
int& ref = num;
auto         a = ref;   // int
decltype(ref) b = ref;  // int&

4. decltype 双括号

  • 单括号 decltype(x)推导的是 变量本身类型
  • 双括号 decltype((x))推导的是 变量的引用类型
int x = 10;
decltype(x)   a;  // int
decltype((x)) b;  // int&

5. C++11 返回值后置:auto + decltype

C++11 模板函数无法直接推导返回值,诞生了 decltype(auto) 前置语法。

template<typename T1, typename T2>
auto add(T1 a, T2 b) -> decltype(a + b)
{
    return a + b;
}

6. 区别

特性 const constexpr
主要作用 只读保护 编译期求值
变量初始化 可以运行时初始化 必须常量表达式
修饰函数 不能修饰函数(C++前) C++11 起支持编译期函数
数组大小 不一定可用 可以做编译期数组大小
对象 可以修饰运行时对象 可以编译期构造对象
是否隐式带 const

7. 总结

  • auto 和 decltype 的区别?
    auto 根据初始化值推导,必须初始化;decltype 根据表达式推导,无需初始化。
    auto 丢失 const、引用;decltype 完全保留。
    auto 适合日常变量定义;decltype 适合精准类型推导、模板编程。
  • decltype (x) 和 decltype ((x)) 区别?
    decltype(x):变量本身类型
    decltype((x)):左值表达式,推导出 引用类型
  • auto 和 decltype (auto) 区别?
    auto:值推导,会退化
    decltype(auto):完全保留属性,不退化