--- tags: CSE --- ```auto``` type deduction is just like template type deduction. ## Case 1: The type specifier is a pointer or reference, but not a universal reference. ```cpp= int x; const int arr[N]; auto& rx = x; // type is int& auto* px = &x; // type is int* auto& ra = arr; // type is const int (&) [N] auto* pa = arr; // type is const int* ``` ## Case 2: The type specifier is a universal reference. ```cpp= int x; auto&& ux = x; // type is int& auto&& uv = 0; // type is int&& ``` ## Case 3: The type specifier is neither a pointer nor a reference. ```cpp= int x; const char s[] = "0123"; void func(int, double); auto v = x; // type is int auto arr1 = s; // type is const char * auto pf = func // type is void (*)(int, double) ``` --- __but there's one exception:__ ```cpp= auto x1 = 0; // type is int auto x2(0); // type is int auto x3 = {0}; // type is std::initializer_list<int> auto x4{0}; // type is int ``` the treatment of braced initializers is the only way where ```auto``` type deduction and template type deduction differ. ```cpp= auto x = {0,1,2}; // type is std::initializer_list<int> template<typename T> void f(T param); f({0,1,2}); // can't deduce type for T f(x); // but this one works, // T is std::initializer_list<int>, // ParamType is std::initializer_list<int> template<typename T> void f(std::initializer_list<T> initList); f({0,1,2}); // now T is deduced as int, and ParamType is std::initializer_list<int> ``` --- in c++14, ```auto``` as a return type of function is vaild. but in that use of ```auto```, type deduction employ template type deduction, not ```auto``` type deduction. so a function which returns a braced initializer with an ```auto``` type won't compile. ```cpp= auto createInitList() { return {0, 1, 2}; // error. } ``` even lambda which's using ```auto``` as a parameter can't. (c++14) ```cpp= vector<int> v; auto resetV = [&v](const auto& newValue) { v = newValue; }; resetV({0,1,2}); ``` even in c++20, function with a ```auto``` type as a parameter can't. ```cpp= void f(auto param); f({0,1,2}); // error. ``` --- reference: - Effective Modern C++ 1/e, Scott Meyers - https://isocpp.org/wiki/faq/cpp14-language#generic-lambdas - https://stackoverflow.com/questions/29944985/is-there-a-way-to-pass-auto-as-an-argument-in-c