Auto type deducing
基本上和模板的类型推测是一样的 ,除了一种情况
eg.
1 auto x=27 // x is int 2 const auto cx=x //cx is const int 3 const auto & rx=x // rx is referance of int
//同样的对于右值引用
auto&& uref1 =x //uref1 is int and lvalue auto&& uref2 = rx //uref2 is int& and lvalue auto&& uref3 = 27 //uref3 is int&& and rvalue
//同样对于function 和 array
cosnt char name[]={"XXX"}// name is const char[13] auto arr1 = name; // arr1 is const char * auto& arr2 = name //arr2 is const char (&)[13] void func(int ,double) auto func1 = func// func1 is void *(int ,double) auto& func2 = func// func1 is void (&)*(int ,double)
注意事项:
1.使用auto关键字的变量必须有初始值
2.可以用 Valatile , *(指针) ,&(引用) ,&&(rvalue引用)修饰auto
3.函数参数和模板参数不能被声明为auto
4.auto不能自动推导出顶层的qualifiers和引用类型,除非显示说明
去掉&
去掉const
5.对于数组类型 auto会推导为对应类型的指针
唯一的区别是在用花括号的时候 eg {1,2,3,4}
auto x = {1,2,3,4}//x is a std::initializar_list<int> // x被解释为初始化列表 ,而 template <typename T> void f(T param) f({1,2,3,4}); //无法解释 error!
另外 在c++14里
auto creatList(){ return {1,2,3,4} ; } //error! can not deduce type
同样 lamada中
std::vector<int> v; auto resetV=[&v](const auto& new value){ v = newValue };//c++14 resetV({1,2,3,4}) // error! can not deduce type