C ++ 11 New Feature Notes

来源:互联网 发布:淘宝卖自家产大米 编辑:程序博客网 时间:2024/06/08 06:41

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 initializererror C3536: 'fib': cannot be used before it is initializederror 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


0 0