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

 



转载于:https://www.cnblogs.com/zhanghengyu/p/10885691.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值