auto和decltypeC++11
- auto和decltype
C++14
C++17
C++20
持续更新…
auto类型推导:C++11引用auto和decltype关键字,使用它们可以在编译期就推导出变量或者表达式的类型。
decltype推导规则:
- 通过=右边的类型推导出变量的类型:auto a = 10; // 10是int型,可以自动推导出a是int
推导限制:
auto的使用必须马上初始化,否则无法推导出类型:auto e; // error,使用auto必须马上初始化,否则无法推导类型
auto在一行定义多个变量时,各个变量的推导不能产生二义性,否则编译失败:auto d = 0, f = 1.0; // error,0和1.0类型不同,对于编译器有二义性,没法推导
auto不能用作函数参数:void func(auto *value*) {} // error,auto不能用作函数参数
在类中auto不能用作非静态成员变量:
class A { auto a = 1; // error,在类中auto不能用作非静态成员变量 static auto b = 1; // error,这里与auto无关,正常static int b = 1也不可以 static const auto c = 1; // ok };auto不能定义数组,可以定义指针:auto c[10] = a; // error,auto不能定义数组,可以定义指针
auto无法推导出模板参数:
vectord; vector f = d; // error,auto无法推导出模板参数 在不声明为引用或指针时,auto会忽略等号右边的引用类型和const 和volatile限定
在声明为引用或者指针时,auto会保留等号右边的引用和const 和volatile属性
int i = 0; auto *a = &i; // a是int* auto &b = i; // b是int& auto c = b; // c是int,忽略了引用 const auto d = i; // d是const int auto e = d; // e是int const auto &f = e; // f是const int& auto &g = f; // g是const int&
auto和decltype配合使用推导规则:
decltype则用于推导表达式类型,这里只用于编译器分析表达式的类型,表达式实际不会进行运算。
对于decltype(exp)有
exp是表达式,decltype(exp)和exp类型相同
exp是函数调用,decltype(exp)和函数返回值类型相同
其它情况,若exp是左值,decltype(exp)是exp类型的左值引用
decltype会保留表达式的引用和const 和volatile属性
int a = 0, b = 0; decltype(a + b) c = 0; // c是int,因为(a+b)返回一个右值 decltype(a += b) d = c;// d是int&,因为(a+=b)返回一个左值 d = 20; cout << "c " << c << endl; // 输出c 20
返回值后置类型语法就是为了解决函数返回值类型依赖于参数但却难以确定返回值类型的问题
templateauto add(T t, U u) -> decltype(t + u) { return t + u; }



