2.auto
条款05:优先选用auto,而非显示型别声明
int x; //忘记初始化
template<typename It>
void dwim(It a,It b){
while(a!=b){
typename std::iterator_traits<It>::value_type
currValue = *b; //定义又臭又长
}
}
auto x=5; //必须初始化
template<typename It>
void dwim(It a,It b){
while(a!=b){
auto currValue = *b; //只需要auto即可
}
}
//一般是有lambda的时候都是用auto,不然你拿捏不了型别
auto func=[](int a,int b){return a==b;};
auto func_auto=[](auto a,auto b){return a==b;};
//不用auto也是可以声明lambda表达式的,可以用std::function,但是会啰嗦,以及占用更多的内存。
function<bool(const std::unique_ptr<Widget>&,
const std::unique_ptr<Widget>&)>
dereFUPLess = [](const std::unique_ptr<Widget>&p1,
const std::unique_ptr<Widget>&p2){return *pa<*p2;};
//可以看到,上面的声明巨麻烦,并且std::function会占用更多的内存当使用auto推导的型别不符合要求的时候,使用带显式型别的初始化物习惯用法
Last updated
