C ++ 11 New Feature Notes

Lambda

Anonymous functions, called lambda, have been added to C ++ and quickly rose to prominence. It is a powerful feature borrowed from functional programming, that in turned enabled other features or powered libraries. You can use lambdas wherever a function object or a function object or a functor or a std::function is expected. You can read about the syntax here.

For a description of lambda expressions, see Lambda Expressions in C++.


<strong style="background-color: rgb(204, 204, 204);"><span style="font-family:Arial;font-size:14px;">std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);

std::for_each(std::begin(v), std::end(v), [](int n) {std::cout << n << std::endl;});

auto is_odd = [](int n) {return n%2==1;};
auto pos = std::find_if(std::begin(v), std::end(v), is_odd);
if(pos != std::end(v))
  std::cout << *pos << std::endl;</span></strong>

 
A bit trickier are recursive lambdas. Imagine a lambda that represents a Fibonacci function. If you attempt to write it using auto you get compilation error: 

<strong style="background-color: rgb(204, 204, 204);"><span style="font-family:Arial;font-size:14px;">auto fib = [&fib](int n) {return n < 2 ? 1 : fib(n-1) + fib(n-2);};</span></strong>
<strong style="background-color: rgb(204, 204, 204);"><span style="font-family:Arial;font-size:14px;">
</span></strong>
<strong style="background-color: rgb(204, 204, 204);"><span style="font-family:Arial;font-size:14px;">error C3533: 'auto &': a parameter cannot have a type that contains 'auto'
error C3531: 'fib': a symbol whose type contains 'auto' must have an initializer
error C3536: 'fib': cannot be used before it is initialized
error C2064: term does not evaluate to a function taking 1 arguments</span></strong>

The problem is auto means the type of the object is inferred from its initializer, yet the initializer contains a reference to it, therefore needs to know its type. This is a cyclic problem. The key is to break this dependency cycle and explicitly specify the function's type using std::function.

<span style="background-color: rgb(204, 204, 204);"><strong><span style="font-family:Arial;font-size:14px;">std::function<int(int)> lfib = [&lfib](int n) {return n < 2 ? 1 : lfib(n-1) + lfib(n-2);};</span></strong></span>


Original Link: http://www.codeproject.com/Articles/570638/Ten-Cplusplus-Features-Every-Cplusplus-Developer


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值