auto&decltype
C++98:
auto int a = 10;//自动变量(相对于static, register,extern,可以省略)
//新标准废弃这种用法
C++11:
int a = 10;
auto 仅仅是一个占位符,并不是一个真正的类型。根据初始化的值推断变量的类型
auto的作用
1.代替较长的声明
std::vector<std::string>strary;
for(std::vector<std::string>::iterator it = strary.begin();it!=strary.end();it++)
{}
for(auto it = strary.begin();it!=strary.end();it++){}
2.模板函数记录结果或者优化计算
template<typename _Tx, typename _Ty>
void Add(_Tx x, _Ty y)
{
auto res = x+y;
std::cout<<res;
}
优化计算:
#define MAX(a,b)({\
auto _a = (a);\
auto _b = (b);\
(_a > _b)? _a : _b;
})
auto注意事项
auto变量必须在定义时初始化:
auto a;//err
auto a = 10;
auto x {1};
auto z = new auto(1);
定义一个auto序列变量推导成同一类型:
auto a1 = 10,a2='A',a3=3.14;//err;
auto a1= 10,a2 = 20,a3 = 30;//Ok
如果初始化表达式是引用,则去除引用:
int a = 15;
int &b = a;
auto c = b//c为int 而不是int&(去除引用)
auto&d=b; d 为 int&
c = 20; a不变
d = 20; a 变为20
初始化表达式为const或volatile(或both),则去除const/volatile:
const int a = 10;
auto b = a;//b 为非const int (去除const)
const auto c = a;//c 为const int
b = 20;//ok
c = 20;//err
auto带上&号,不去除const:
const int a = 10;
auto &b = a;//auto 带上&, 所以不去除const,b为const int
b = 10; //err
初始化表达式为数组时,auto关键字推导类型为指针:
int a[3] = {0,1,2};
auto b = a;
auto c[3] = a;//err
cout<<typeid(b).name() <<endl;
若数组且auto带上&,则推导类型为数组类型:
int a[3] = {0,1,2};
auto& b = a;
cout<<typeid(b).name() <<endl;
函数或者模板参数不能被声明为auto:
void func(auto x);//err
非静态成员
struct stu{
auto val = 10;//err 非静态成员
}
模板参数不可以
vector<auto>v={2};//err
decltype
在定义变量的时候,有时希望从表达式中推断出要定义变量的类型,但又不想用表达式的值去初始化变量(auto)。还有可能是函数返回类型为某表达式的值类型,这时候auto就不能用了,C++11又引入了decltype,作用是选择并返回操作数的数据类型,在此过程中,编译器只是分析表达式并得到它的类型,不计算表达式的值
- 单个标记表达式以及访问类成员,推导为本类型
- 将亡值,推导为类型的右值引用
- 左值推导为左值引用
- 以上都不是,推导为本类型
auto结合decltype返回值占位
template<typename _Tx, typename _Ty>
auto Add(_Tx x, _Ty y)->decltype(x+y)
{
return x+y
}
const int x =2 ,&b = a;
decltype(a) x = 0;//x类型为const int
auto z = a;//z类型为int
decltype(b)y = x; //y类型为 const int&
auto z = b; // z类型为int
int i = 2;
decltype(i) int类型
decltype((i)) int& 类型
int i = 21;
decltype(i = 54)x = i; // 赋值语句 decltype(i = 54)不运行 返回的是int& x 是i 的引用
int arr[20] = {};
decltype(arr)b; //b 20个元素数组