🐭 auto 类型推导与模板类型推导
auto 类型推导与模板类型推导大致遵循相同的规则,它们之间的对应关系为 (auto <=> T):
代码示例 :
#include <iostream>// template type deduction// case 1: param's type is a reference or pointertemplate <typename T> void f(T ¶m);template <typename T> void f(T *param);// case 2: param's type is a universal referencetemplate <typename T> void f(T &¶m);// case 3: param's type is a value typetemplate <typename T> void f(T param);int main(void) {int x = 42;int &rx = x;const int cx = x;const int &crx = cx;// auto type deduction// case 1: param's type is a reference or pointerauto ¶m11 = rx; // param11 is `int &`auto ¶m12 = crx; // param12 is `const int&`auto *param13 = &x; // param13 is `int *`auto *param14 = &cx; // param14 is `const int *`// case 2: param's type is a universal referenceauto &¶m21 = x; // param21 is `int &`auto &¶m22 = cx; // param22 is `const int&`auto &¶m23 = std::move(x); // param23 is `int &&`auto &¶m24 = std::move(cx); // param24 is `const int &&`// case 3: param's type is a value typeconst volatile int &cvrefx = x;const int *const cpcx = &x;int ax[2] = {x, x};auto param31 = cvrefx; // param31 is `int`auto param32 = cpcx; // param32 is `const int*`auto param33 = ax; // param33 is `int*`return 0;}
🐂 auto 类型推导与 std::initializer_list
auto 会将大括号初始化当成 std::initializer_list
- 拷贝初始化
- 直接初始化,C++17 新增的规则
- 当 auto 作为函数返回值与 Labmda 形参时无法推导初始化列表
模板不会推导初始化列表,除非模板形参为初始化列表类型。 :::tips auto 作为函数返回值与 Labmda 形参时,实际上遵循的是模板类型推导规则 ::: 代码示例 :
#include <initializer_list>template <typename T> void f(T){};template <typename T> void g(std::initializer_list<T>){};int main(void) {// case 1: auto deduction initializer listauto x11 = 27; // x11 is intauto x12(27); // x12 is intauto x13 = {27}; // copy-initialisation, x13 is std::initializer_list<int>auto x14{27}; // direct-initialisation (until C++17), x14 is int// case 2: auto deduction invalid case// auto x21 = {1, 2.0}; // error: conflicting types// auto x22{1, 2}; // error: not a single value// case 3: auto deduction for function return value// auto ints = []() { return {1, 2, 3}; }; // error: can not deduce initializer list// case 4: auto deduction for lambda function parameterauto printv = [](const auto &v) {};// printv({1, 2, 3}); // error: can not deduce initializer list// case 5: template deduction initializer list// f({1, 2, 3, 4, 5, 6}); // error: can not deduce initializer listauto x5 = {1, 2, 3, 4, 5, 6}; // std::initializer_list<int>f(x5); // work aroundg({1, 2, 3, 4, 5, 6});return 0;}
:::tips 虽然模板不能推导初始化列表,但是可以结合 auto 来间接支持,比如上面代码中的 x5 的使用 :::
🐯 总结
- auto 类型推导与模板类型推导大致遵循相同的规则
- auto 作为函数返回值与 Labmda 形参时,实际上遵循的是模板类型推导规则
- auto 类型推导与模板类型推导的唯一区别是 auto 作为变量使用时可以推导 std::initializer_list
