Files
Data-Structure/Features-Cpp/C11/auto自动推导.MD
2025-08-28 21:17:28 +08:00

109 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

好,那我就帮你系统性地整理一份 **C++ 中 `auto` 与 lambda 函数的知识大全**,把语法细节、坑点、进阶用法都讲全,让你能用到开发级别。
我会先分两部分:
1. `auto` 关键字大全
2. Lambda 函数大全
最后会给出它们的 **联合应用技巧**
---
## 1. `auto` 关键字大全
### 1.1 基础概念
* **作用**:让编译器自动推导变量、函数返回值、模板参数的类型。
* **推导时间**:编译期完成(不影响运行时性能)。
* **核心限制**
* 必须有初始化值(除非是函数返回类型或形参声明中)。
* 不能推导为 **数组类型**(会退化为指针)和 **函数类型**(会退化为函数指针)。
---
### 1.2 基本用法
```cpp
auto x = 10; // int
auto y = 3.14; // double
auto ptr = &x; // int*
auto str = "Hello"; // const char*
```
---
### 1.3 `auto` 推导规则
假设初始化表达式类型为 `T`
1. **普通变量**:直接推导为 `T`
2. **有引用**
```cpp
int a = 5;
int& r = a;
auto x = r; // int引用被忽略
```
3. **有 const**
```cpp
const int a = 5;
auto x = a; // int顶层 const 被忽略)
```
4. **保留引用和 const**:需要 `auto&` / `const auto&`
```cpp
const int a = 5;
auto& r = a; // const int&
const auto& cr = a; // const int&
```
---
### 1.4 特殊形式
* **`auto*`**:明确推导为指针类型
* **`decltype(auto)`**保留完整类型信息包括引用、const
```cpp
int x = 1;
int& r = x;
auto a = r; // int
decltype(auto) b = r; // int&
```
---
### 1.5 在函数中
* **返回类型推导**
```cpp
auto add(int a, int b) { return a + b; } // 返回 int
```
* **尾返回类型**
```cpp
template<class T, class U>
auto add(T a, U b) -> decltype(a+b) { return a+b; }
```
---
### 1.6 常见坑
* **不同返回类型不能推导**
```cpp
auto test(bool b) {
if (b) return 1; // int
else return 1.5; // double
} // ❌ 编译错误
```
* **列表初始化可能推导成 `std::initializer_list`**
```cpp
auto x = {1, 2, 3}; // std::initializer_list<int>
```
---