Skip to content

Commit 010d6f3

Browse files
committed
update auto param
1 parent 07494f6 commit 010d6f3

File tree

1 file changed

+51
-11
lines changed

1 file changed

+51
-11
lines changed

docs/auto.md

+51-11
Original file line numberDiff line numberDiff line change
@@ -16,39 +16,39 @@ int f();
1616
1717
> {{ icon.detail }} 当初引入后置返回类型实际的用途是 `auto f(int x) -> decltype(x * x) { return x * x; }` 这种情况,但很容易被接下来 C++14 引入的真正 `auto` 返回类型推导平替了。
1818
19-
C++14 引入了函数**返回类型推导**`auto` 才算真正意义上能用做函数返回类型,它会自动根据函数中的 `return` 表达式推导出函数的返回类型。
19+
但是 C++14 引入了函数**返回类型推导**`auto` 才算真正意义上能用做函数返回类型,它会自动根据函数中的 `return` 表达式推导出函数的返回类型。
2020

2121
```cpp
2222
auto f(int x) {
23-
return x * x; // 表达式 `x * x` 的类型为 int,所以 auto 类型推导为 int
23+
return x * x; // 表达式 `x * x` 的类型为 int,所以 auto 类型推导为 int
2424
}
2525
// 等价于:
2626
int f() {
27-
return x * x;
27+
return x * x;
2828
}
2929
```
3030
3131
如果函数中没有 `return` 语句,那么 `auto` 会被自动推导为 `void`,非常方便。
3232
3333
```cpp
3434
auto f() {
35-
std::println("hello");
35+
std::println("hello");
3636
}
3737
// 等价于:
3838
void f() {
39-
std::println("hello");
39+
std::println("hello");
4040
}
4141
```
4242

4343
值得注意的是,返回类型用 `auto` 来推导的函数,如果有多条 `return` 语句,那么他们必须都返回相同的类型,否则报错。
4444

4545
```cpp
4646
auto f(int x) {
47-
if (x > 0) {
48-
return 1; // int
49-
} else {
50-
return 3.14; // double
51-
}
47+
if (x > 0) {
48+
return 1; // int
49+
} else {
50+
return 3.14; // double
51+
}
5252
} // 错误:有歧义,无法确定 auto 应该推导为 int 还是 double
5353
```
5454
@@ -68,7 +68,47 @@ auto f() { // 编译通过:auto 推导为 int
6868

6969
C++20 引入了**模板参数推导**,可以让我们在函数参数中也使用 `auto`
7070

71-
TODO: 介绍
71+
在函数参数中也使用 `auto` 实际上等价于将该参数声明为模板参数,仅仅是一种更便捷的写法。
72+
73+
```cpp
74+
void func(auto x) {
75+
std::cout << x;
76+
}
77+
// 等价于:
78+
template <typename T>
79+
void func(T x) {
80+
std::cout << x;
81+
}
82+
83+
func(1); // 自动推导为调用 func<int>(1)
84+
func(3.14); // 自动推导为调用 func<double>(3.14)
85+
```
86+
87+
如果参数类型的 `auto` 带有如 `auto &` 这样的修饰,则实际上等价于相应模板函数的 `T &`。
88+
89+
```cpp
90+
// 自动推导为常引用
91+
void func(auto const &x) {
92+
std::cout << x;
93+
}
94+
// 等价于:
95+
template <typename T>
96+
void func(T const &x) {
97+
std::cout << x;
98+
}
99+
100+
// 自动推导为万能引用
101+
void func(auto &&x) {
102+
std::cout << x;
103+
}
104+
// 等价于:
105+
template <typename T>
106+
void func(T &&x) {
107+
std::cout << x;
108+
}
109+
```
110+
111+
### `auto` 在多态中的妙用
72112

73113
传统的,基于类型重载的:
74114

0 commit comments

Comments
 (0)