auto
- auto关键字不是C++11才引入的之前就有,C++11标准将auto关键字实现为自动类型推断
- auto关键字其实就是让编译器通过初始值来推断变量的类型,因此auto定义的变量必须有初始值(必须进行显式初始化)
int x = 10;
auto y = x; //y的类型为int
auto z; //未初始化,无法推断
static auto w; //隐式初始化,无法推断
- auto的用法:
(1)基本用法:
auto x = 10; //x为int类型
int y = 10;
double w = 20.5;
auto z = y + w; //y + w为double类型所以z为double类型
(2)auto与引用
int x = 10, *ptr = &x;
auto y = x; //y为int类型
auto & z = x; //z为x的引用
auto ptr1 = ptr; //ptr1为int * 类型
auto * ptr2 = ptr; //ptr2也为int * 类型
(3)auto与const
const int x = 10;
auto y = x; //y仍然为int类型而不是const int
const auto y = x; //此时y才为const int 类型
(4)auto与函数变量
double func(int);
auto func1 = func; //func1为double(*)(int)类型
- auto一般用于类型名比较冗长或者不明确的情况
vector<int> nums{1, 2, 3, 4, 5};
for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)
//替换为
for(auto iter = nums.begin(); iter != nums.end(), iter++)
decltype
1.C++11引入关键字decltype将变量的类型声明为表达式指定的类型,其实就是从表达式中推断出要声明的变量的值
2. 与auto关键字不同,利用decltype定义变量可以不进行初始化
3. decltype的用法:
(1)基本用法:
int x = 10;
decltype(x) y; //y和x的类型相同仍然是int类型
(2)decltype与const
const int x = 10;
decltype(x) y = 20;
y = 30; //错误的,y的类型为const int
(3)decltype与引用
const int x = 10;
const int &y = x;
decltype(y) z = x; //z为const int&类型
decltype((x)) w = x;
- 若表达式类型不是引用类型,但我们需要推断出引用类型,可以在表达式外添加一对括号,就变成了引用类型
(4)decltype与指针
int x = 10, y = 20;
int * ptr = &x;
decltype(ptr) ptr2 = &y; //ptr2为int * 类型,指向y
decltype(*ptr) z = y; //z为int &类型,引用y
- 对指针的解引用返回的是引用类型
(5)decltype与函数
int show() {return 10;}
decltype(show()) y = 20; //y的类型为int类型
- 编译器只是通过分析表达式或函数然后得到他的类型,并不会真实去执行函数或计算表达式的值
- decltype主要用于模板的定义,以为只有等到实例化后才能知道确定类型:
返回值后置
- 返回值后置是C++11新增的一种函数声明的语法,返回值的类型放在参数列表后面
- 返回值后置一般用于无法确定返回值类型的场景下,一般也是在模板中使用
- 返回值后置通常要借助auto关键字和decltype关键字完成
double func(int x); //原始函数声明的方法
auto func(int x)->double
template <typename T, typename U>
auto func(T &, U &) -> decltype(T*U)
{
return T*U;
}