auto关键字作用
自动变量类型推导
在定义变量时,使用auto可以让变量定义为初始化的值类型。
auto a = 1; auto b = string("123");
返回变量类型推导
在模板函数内,返回值可以省去类型,由编译器推导。如果在C++11旧版本,需要使用decltype关键字手动推导。
template<typename T, typename S> auto add(T x, S y) { return x + y; } int main(){ string a = "123"; char b[] = "456"; cout << add(a, b); return 0; }
匿名函数参数推导
匿名函数无法使用模板来推导参数变量类型,所以直接用auto代替即可。
int main(){ string a = "123"; char b[] = "456"; auto f = [](auto t, auto s) { return t + s; }; cout << f(a, b); return 0; }
非类型模板参数推导
如果模板中使用了非类型参数,可以用auto代替其类型。
template<auto g> auto f(){ return g; } int main(){ cout << f<10>(); return 0; }
结构化绑定定义变量
可以一次性定义一组变量。变量的类型可以不同。 int main(){ auto [a, b] = pair(1, 2.3); auto [c, d, e] = tuple('4', "5", string("6")); cout << a << b << c << d << e; return 0; }