<span style="font-size:18px;">//const 与auto和decltype
const int a(4);
auto aa(a);//int
const auto aa2(a);//const int 可以通过加上const使得aa2被顶层const修饰
decltype(a) ad (4);//const int
const decltype(a) ad2(4);//const 也可以加但是多余
const int*a1(&a);
auto a1a(a1);//const int * auto能够识别底层const
decltype(a1) a1d;//const int *
//constexpr 与auto和decltype
constexpr int b(4);
auto ba(b);//int
decltype(b) bd (4);//const int
//bd并不解释为decltype int 类型而是 const int类型。这正说明decltype是const一种特殊情况
// &与auto和decltype
const int &d(4);
struct my2 {
auto da(d);//auto变量不能放到结构体里面
};
auto da(d);//int 通过表达式结果的类型推断
struct my {
decltype(d) dd;
};
cout << sizeof(my) << endl;//4
decltype(d) dd(4);//const int & decltype与表达式的类型密切相关
//[] 与auto和decltype
int e[5];
auto ea(e);//int * 编译器最终将[]解析成指针同时auto又是通过表达式结果的类型推断
decltype(e) ed;//int ed[5]
//() 与auto和decltype
int f();
auto fa(f);//int (*fa)()
decltype(f) fd;//int fd();
</span>
由上述代码可总结出 区别:
auto是通过初始值表达式的返回结果推断其类型,也可以说是编译后的类型,所以对于初始值表达式为数组 引用 顶层const函数 等通过auto得到的类型出入比较大。
Decltype推断对象的类型与表达式形式密切相关。所以所以对于初始值表达式为数组 引用 顶层const函数 等通过decltype完全一致。特别的对于表达式的结果为左值时(包括 * 、前置++ -- 、 (表达式)),推断出引用类型。
通过这些区别,我们可以得到他们的应用:
<span style="font-size:18px;"> int a(4);
auto aa(a);//拷贝一个变量的类型和值
decltype(a) ad(a);//拷贝一个变量的类型和值
int array[5];
decltype(array) c;//创建一个同样的数组,在不知道array元素个数的情况下
int ra[10][2];
decltype (ra) rac;//完美拷贝其类型
int(*f[2])();
decltype (f) fc;</span>