c++11---类型推导

个人主页:pp不会算法v
版权: 本文由【pp不会算法v】原创、在CSDN首发、需要转载请联系博主
如果文章对你有帮助、欢迎关注、点赞、收藏(一键三连)和订阅专栏哦

c++11新特性及工程级应用系列文章

一、类型推导auto/decltype

简介

auto:
关键字用于在编译时自动推导变量的类型。在初始化变量时使用auto,编译器会根据等号右边的表达式推导出变量的类型,并将其替换为实际的类型。
示例:auto x = 10;,编译器会推导x的类型为int。 auto适用于简化代码,减少类型冗余,提高可读性和灵活性。

decltype:
关键字用于查询表达式的类型,而不是推导变量的类型。它返回表达式的静态类型,包括顶层const和引用。
示例:decltype(x) y;,y的类型将与x的类型一致。
decltype适用于需要获取表达式类型的场景,如模板元编程、函数返回类型声明等。

用了因不影响性能

可能我们对这个类型推导默认它会影响性能,至少我开始是这么以为的
但是你要知道的是他是编译的时候推到的并不是运行的时候推导的,所以顶多知识编译的时间可能长一点,但是编译好之后就是对应的类型定下来了,而且有个好处避免了一些隐式类型转换,类型更加准确,所以应该多用,唯一的缺点式我感觉就是代码不便于阅读

测试代码

/**
 * 类型推导
 */
#include
#include
using namespace std;
void type_test1()
{
	//推导基本类型
	auto a = '1';
	cout << "type of a:" << typeid(a).name() << endl;
	//推导指针
	auto b = new int(1);
	cout << "type of b:" << typeid(b).name() << endl;
	cout << b << endl;
	delete b;
	b = nullptr;
	//推导数组
	int arr[3] = { 1,2,3 };
	auto c = arr;
	cout << "type of c:" << typeid(c).name() << endl;
	for (int i=0;i<3;i++)
	{
		cout << c[i] << '\r';
	}
	cout << endl;
	//推导自定义类型
	class test{
	public:
		int a, b;
		test(int a,int b):a(a),b(b) {}
	};
	auto d = test(1, 2);
	cout << "type of d:" << typeid(d).name() << endl;
	cout << d.a << "\r" << d.b << endl;
	//静态类型
	static auto e = 0;
	cout << "e=" << e << endl;
	e++;
	//const类型
	const auto f = "12";
}


void type_test2()
{
	int a;
	decltype(a) b = 0;
	cout <<"type of b:"<< typeid(b).name() << endl;
	//和auto差不多就是语法不一样
}

//推导函数返回值类型---这个是c++14新增的
decltype(auto) te()
{
	return 1;
}


void autoTypeTest()
{
	cout << "auto test:" << endl;
	type_test1();//e=0
	type_test1();//e=1
	cout << "decltype test:" << endl;
	type_test2();
}

测试效果:
c++11---类型推导_第1张图片

你可能感兴趣的:(c++,算法,开发语言,c++11)