闲话
今天是 2023 年 4 月 23 日,俺开始正式学习面试相关内容了。打算先从 Effective Modern C++ 这本书开始学起,作为日后代码风格、习惯的指导。不过俺没有一起学习的小伙伴,qwq。
与 ICPC 切割之后,内心都轻松了许多。小醉一宿之后还是十分愉悦的。
欢迎加入 C++ 学习群:https://jq.qq.com/?_wv=1027&k=TW7t8caN
我在微云中上传了 Effective Modern C++ 英文版 pdf:https://share.weiyun.com/nO38Xq2l
中文 mdBook: https://cntransgroup.github.io/EffectiveModernCppChinese/,翻译得十分不错,在我学习过程中没有太多问题[1]。
这书从 \(42\) 个条款item向读者展现了「更高效的 C++」,在列叔叔的入门博客。对我这样的 C++ 初学者十分友好。
引言部分
左值与右值
通常,判断一个表达式是否为左值的小技巧:是否能取得其地址。
一个表达式的类型与它是否是左值、右值无关。即使函数形参是右值引用类型(void func(Foo &&foo) { }),它也依然是左值。
第一章:类型推导
条款一:理解模板的类型推导
模板函数 template <class T> void func(Foo foo) { } 中,Foo 也许不与 T 相同,例如 const T&。在推导时,一般我们会希望传入的 foo 类型与 T 相同,这样 Foo 就能够正确处理。然而有时候 T 的推导会综合 T 和 Foo 二者考虑。
分几种情形考虑:
-
Foo是一个指针/引用,但不是万能引用。
步骤如下:- 若
foo表达式类型是引用,忽略引用。 - 将
foo的类型与Foo的类型进行模式匹配,以推导T。对,就是你想的那个字符串模式匹配,一个萝卜一个坑你总知道吧~
案例 1:
Foo为T&TFoofoo定义 / 传入 intint&intint foo = 1const intconst int&const intconst int foo = 1const intconst int&const intconst int& foo = bar案例 2:
Foo为const T&TFoofoo定义 / 传入 intconst int&intint foo = 1intconst int&const intconst int foo = 1intconst int&const intconst int& foo = bar案例 3:
Foo为T*TFoofoo定义 / 传入 intint*int*&barconst intconst int*const int*const int* foo = &bar - 若
-
Foo是一个万能引用,即T&&。
规则有些特别:
1. 若foo是左值,则T被推导为左值引用。
注意
2. 若foo是右值,则按照上一情形。TFoofoo定义 / 传入 intint&&右值 1int&int&左值 int foo = 1const int&const int&左值 const int foo = 1const int&const int&左值 const int& foo = bar -
Foo既不是指针,也不是引用。
待更新 ↩︎