auto类型转换
auto是C++中常用的一个关键字,我们经常使用auto来进行类型的推导。
例如有时我们进行赋值时,写出变量所属的类型是十分麻烦的,但是我们使用auto代码会显得比较简洁。
//当我们存在如下的使用
template <typename It>
void dwim(It a, It b) {
typename std::iterator_traits<It>::value_type currValue = *b;
....
}
//我们可以使用auto
template <typename It>
void dwim(It a, It b) {
auto currValue = *b;
....
}
下面将介绍auto类型推导的原理
(1)如果初始化表达式的是引用,那么在推导的过程去除引用。
int a = 23;
int &b = a;
auto c = b;
那么c的类型为int;而不是int&
(2)如果初始化表达式为const或volatile(或者两者兼有),则除去const/volatile语义。
const int a1 = 10;
auto b1= a1; //b1的类型为int而非const int(去除const)
const auto c1 = a1;//此时c1的类型为const int
b1 = 100;//合法
c1 = 100;//非法
(3)如果auto关键字后面带上&号,则不去除const语意。
//例如
const int a = 100;
auto & b = a; //其中auto推导出来的类型为const int
(4)初始化表达式为数组时,auto关键字推导类型为指针。
#include <iostream>
int main() {
int array[3] = {0, 1, 2};
auto array1 = array; //auto推导出来的类型是int *
//可以使用boost库或者typeid进行测试
return 0;
}
(5)若表达式为数组且auto带上&,则推导类型为数组类型。
#include <iostream>
int main() {
int array[3] = {0, 1, 2};
auto& array1 = array; //auto推导出来的类型是int(&)[3]
return 0;
}