- 一般情况,auto推导与模板类型推导一致,唯一不同是auto可使用{}进行推导,模板不行
- c++14在函数返回值或者lambda形参中使用auto时,使用的是模板推导而不是auto推导,因此{}使用需注意
#include#include #include using namespace std; void someFunc(){ } template void f0(T value){ } template void f(std::initializer_list value){ } int main() { auto x = 5; const auto cx = x; //既非指针也非引用 const auto &rx = x; //const 引用 const auto *ptx = &x;//const 指针 auto &rx1 = x; //引用 auto *ptx1 = &x;//指针 auto&& uref1 = 5; //右值 auto&& uref2 = x; // x是左值, auto&& uref3 = cx; auto&& uref4 = rx; auto func1 = someFunc; //退化为函数指针 auto& func2 = someFunc; // 函数引用 const char text[]="xi men 吹雪"; auto arr1 = text;//退化为指针 auto & arr2 = text;//带长度的数组 //c98语法 auto x1 = 27; auto x2(27); //c11语法 auto x3={27}; auto x4{27}; //c11 语法 auto x5={1,2,3}; //error: deduced conflicting types ('int' vs 'double') for initializer list element typeauto x6={1,2,3.1}; // auto x6={1,2,3.1}; f({1,2,3,4}); //auto与模板推导的唯一区别:模板无法使用{} //f1({11});//error: use of undeclared identifier 'f1' f1({11}); //f1({11,2});//error: use of undeclared identifier 'f1' f1({11,2}); }
编译生成的代码如下:
#include#include #include using namespace std; void someFunc() { } template void f0(T value){ } template void f(std::initializer_list value){ } #ifdef INSIGHTS_USE_TEMPLATE template<> void f (std::initializer_list value) { } #endif int main() { int x = 5; const int cx = x; const int & rx = x; const int * ptx = &x; int & rx1 = x; int * ptx1 = &x; int && uref1 = 5; int & uref2 = x; const int & uref3 = cx; const int & uref4 = rx; using FuncPtr_33 = void (*)(); FuncPtr_33 func1 = someFunc; void (&func2)() = someFunc; const char text[14] = "xi men 345220271351233252"; const char * arr1 = text; char const (&arr2)[14] = text; int x1 = 27; int x2 = 27; std::initializer_list x3 = std::initializer_list {27}; int x4 = {27}; std::initializer_list x5 = std::initializer_list {1, 2, 3}; f(std::initializer_list {1, 2, 3, 4}); return 0; }
| auto | 推导 |
|---|---|
| auto x = 5; | int x = 5; |
| const auto cx = x | const int cx = x; |
| const auto *ptx = &x | const int * ptx = &x; |
| auto &rx1 = x; | int & rx1 = x; |
| auto *ptx1 = &x; | int * ptx1 = &x; |
| auto&& uref1 = 5; | int && uref1 = 5; |
| auto&& uref2 = x; | int & uref2 = x; |
| auto&& uref3 = cx; | const int & uref3 = cx; |
| auto&& uref4 = rx; | const int & uref4 = rx; |
| auto func1 = someFunc; | using FuncPtr_33 = void (*)();FuncPtr_33 func1 = someFunc; |
| auto& func2 = someFunc; | void (&func2)() = someFunc; |
| auto arr1 = text; | const char * arr1 = text; |
| auto & arr2 = text; | char const (&arr2)[14] = text; |
| auto x3={27}; | std::initializer_list x3 = std::initializer_list{27}; |


![Effective Modern C++[实践]->理解auto类别推导 Effective Modern C++[实践]->理解auto类别推导](http://www.mshxw.com/aiimages/31/993743.png)
