C++ auto和decltype关键字
C++11新标准引入了auto和declty这两个类型推断关键字,auto的推断是基本上针对赋值类型,而decltype则常常希望重表达式中推断出要定义变量的类型,但是不想用该表达式的值初始化变量。
auto num = 21;//num为int类型,初始值为21
decltype (num) tmp;//tmp为int类型
1. auto
auto可以在一个语句中声明多个变量,但是其基本类型只能有一个
auto i = 0, j = 3.14; //错误,j的推断为double,而i是int
auto i = 0, *j = &i; //正确
2. 区别
- auto类型推断的时候会忽略顶层const,保留底层const,而decltype都会保留, 顶层const和底层const一般针对的是指针和引用,顶层const表示指针本身是一个const,底层const表示指针对象所指的是一个常量,用于申明引用的const为底层const。对于一般的基本类型,C++primer把它看作顶层const。
const int i = 0, &ri = i;
auto j = i; //j是一个整数,顶层const被忽略
auto k = ri; //k是一个整数,ri是i的别名,i本身是一个顶层const
auto m = &i; //m是一个整形指针
auto n = &ri; //n是一个指向整数常量的指针,对常量对象取地址是一种底层const
const int i = 0, &ri = i;
decltype (i) j = 0; //j的类型为const int
decltype (ri) k = j; //k的类型为const int &
decltype (ri) m; //错误,引用必须初始化
- decltype (())的结果永远是引用
int i = 0;
decltype ((i)) j = 21; //j的类型为int &
- decltype推断的时候,针对引用类型,推断的类型必须比初始化的类型更严格
int temp = 7;
const int i = 0, &ri = i;
decltype ((ri)) M = temp;//正确, M为cosnt int &, temp为int
decltype ((temp)) N = i; //错误, N为int &, i为const int
decltype (i) Z = ri; //正确,Z为const int, ri为i的引用为const int
decltype ((i)) Z = ri; //正确,Z为const int, ri为i的引用为const int