C++学习笔记 24 auto

一、auto

  1. 自动类型推导 (个人思考:应该可用于多态的场景)
  2. 二、C++11 尾置类型占位符 (trailing return type)
  3. 别名简化长类型,auto简化别名
  4. 拓展:尾置类型结合 decltype 使用

示例代码:
#include<iostream>
#include<vector>
#include<unordered_map>

//const char* getName() {
//std::string getName() {
//C++ 11 尾置返回类型(trailing return type)
//其中 auto 是一个占位符,函数名后 -> 紧跟的 const char* 才是真正的返回类型。
auto getName() -> const char* {
	return "Cherno";
}

//基础使用,自动识别类型
void testAuto() {
	int a = 10;
	auto b = a;
	auto c = 5.0f;
	auto d = 5.0;
	auto e = 5L;
	short f = 9;
	auto g = f;
	auto h = "Cherno";
	auto i = 'h';

	//硬币的两面性,方便,灵活,但也可能引申出使用的问题
	auto name = getName();

	std::cout << name << std::endl;
}


//简化iterator繁长、冗余类型名称的使用
void testAuto2() {
	std::vector<std::string> strings;
	strings.reserve(2);
	strings.emplace_back("Hello");
	strings.emplace_back("World");
	//for (std::vector<std::string>::iterator it = strings.begin(); it != strings.end(); it++) {
	//用auto简写 长变量	
	for (auto it = strings.begin(); it != strings.end(); it++) {
		std::cout << *it << std::endl;
	}
}

class Device {};
class DeviceManager {
private:
	std::unordered_map<std::string, std::vector<Device*>> m_Devices;
public:
	 std::unordered_map<std::string, std::vector<Device*>> GetDevices() {
		return m_Devices;
	}
};
//自定义长类型名称的简化
void testAuto3() {
	DeviceManager dm;

	//1. 元使用
	std::unordered_map<std::string, std::vector<Device*>> diveceMap = dm.GetDevices();

	//2.1 别名:新版本
	//using DeviceMap = std::unordered_map<std::string, std::vector<Device*>>;
	//2.2 别名:旧版本
	typedef std::unordered_map<std::string, std::vector<Device*>> DeviceMap;
	const DeviceMap& deviceMap2 = dm.GetDevices();

	//3. auto
	//一般来讲,基本上是在类型比较庞大,而且出于某种原因不想使用类型定义(例如:为了简化类型而创建别名)的情况才使用auto
	const auto& deviceMap3 = dm.GetDevices();
}


int main() {
	testAuto();
	testAuto2();
	std::cin.get();
}
posted @ 2025-12-19 10:36  超轶绝尘  阅读(0)  评论(0)    收藏  举报