Commit 010d6f3 1 parent 07494f6 commit 010d6f3 Copy full SHA for 010d6f3
File tree 1 file changed +51
-11
lines changed
1 file changed +51
-11
lines changed Original file line number Diff line number Diff line change @@ -16,39 +16,39 @@ int f();
16
16
17
17
> {{ icon.detail }} 当初引入后置返回类型实际的用途是 ` auto f(int x) -> decltype(x * x) { return x * x; } ` 这种情况,但很容易被接下来 C++14 引入的真正 ` auto ` 返回类型推导平替了。
18
18
19
- C++14 引入了函数** 返回类型推导** ,` auto ` 才算真正意义上能用做函数返回类型,它会自动根据函数中的 ` return ` 表达式推导出函数的返回类型。
19
+ 但是 C++14 引入了函数** 返回类型推导** ,` auto ` 才算真正意义上能用做函数返回类型,它会自动根据函数中的 ` return ` 表达式推导出函数的返回类型。
20
20
21
21
``` cpp
22
22
auto f (int x) {
23
- return x * x; // 表达式 ` x * x ` 的类型为 int,所以 auto 类型推导为 int
23
+ return x * x; // 表达式 ` x * x ` 的类型为 int,所以 auto 类型推导为 int
24
24
}
25
25
// 等价于:
26
26
int f() {
27
- return x * x;
27
+ return x * x;
28
28
}
29
29
```
30
30
31
31
如果函数中没有 `return` 语句,那么 `auto` 会被自动推导为 `void`,非常方便。
32
32
33
33
```cpp
34
34
auto f() {
35
- std::println("hello");
35
+ std::println("hello");
36
36
}
37
37
// 等价于:
38
38
void f() {
39
- std::println("hello");
39
+ std::println("hello");
40
40
}
41
41
```
42
42
43
43
值得注意的是,返回类型用 ` auto ` 来推导的函数,如果有多条 ` return ` 语句,那么他们必须都返回相同的类型,否则报错。
44
44
45
45
``` cpp
46
46
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
+ }
52
52
} // 错误:有歧义,无法确定 auto 应该推导为 int 还是 double
53
53
```
54
54
@@ -68,7 +68,47 @@ auto f() { // 编译通过:auto 推导为 int
68
68
69
69
C++20 引入了** 模板参数推导** ,可以让我们在函数参数中也使用 ` auto ` 。
70
70
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 ` 在多态中的妙用
72
112
73
113
传统的,基于类型重载的:
74
114
You can’t perform that action at this time.
0 commit comments