类推类型与区间迭代

在传统 C 和 C++中,参数的类型都必须明确定义,当我们面对一大堆复杂的模板类型时,必须明确的指出变量的类型才能进行后续的编码,这样很不方便,而向python等语言就要显得智能得多。C++11 引入了 autodecltype 这两个关键字实现了类型推导,让编译器来操心变量的类型。这使得 C++ 也具有了和其他现代编程语言一样,某种意义上提供了无需操心变量类型的使用习惯。

auto关键字

  使用 auto 关键字是一个存储类型说明符,C++11将用于进行类型推导。这个要求进行显示初始化,

auto m = 120; // m是int类型
auto p = &m; // p是int类型指针

以前遍历一个迭代器需要这样做

vector<int>::iterator it;
for(it = vec.begin(); it != vec.end(); it++){
	;
}

有了auto后,遍历方便很多,只需要

for(auto x : vec){
		;
}

注意:auto 不能用于函数传参,这将无法通过编译的(考虑重载的问题,我们应该使用模板)。

decltype 关键字

  关键字decltype 将变量的类型声明为表达式指定的类型。下面语句的意思是让y的类型与x相同:

int x = 5;
decltype(x) y;

再看下面例子

#include<bits/stdc++.h>
using namespace std;

int main(){
	double x;
	decltype(&x) y; // 定义y为double类型指针	
	y = new double{4.0};
	cout << *y << endl;
	return 0;
}

在定义类模板的时候特别有用,因为只有等到模板实例化后才知道具体类型

#include<bits/stdc++.h>
using namespace std;

template<typename T, typename U>
void func(T a, U b){
	decltype (a*b) x;
}

int main(){
	func(2, 2.5); // 此时x是double类型
	func(2u, 6); // 此时x是unsinged int 类型

	return 0;
}

特别注意,decltype指定类型可以是引用或者const,如下例子一样:

#include<bits/stdc++.h>
using namespace std;

int main(){
	int a = 1;
	int &ra = a;
	const int b = 3;
	decltype(b) y = 4;  // y的类型为const int
	int c = 0;
	decltype(ra) x = c; // x的类型是int &
	return 0;
}

尾返回类型

C++11 增加了一种新语法,在函数名和函数列表后面指定返回类型

double f1(double, int);  // 传统语法
auto f2(double, int) -> double;     // 新语法 ,返回double 类型

这种设计将给C++带来很多方便,例如定义一个模板类返回2个数的和,传统方法需要写为:

template<class T, class U, class R>
R add(T a, U b){
	return a + b;
}

由于不知道返回类型,这样传递返回类型是一种很丑陋的写法,有了后置返回类型,上述代码可以写为:

template<class T, class U>
auto add(T a, U b) -> decltype(a + b){
	return a + b;
}
原文地址:https://www.cnblogs.com/td15980891505/p/7411684.html