关于异常:
我们可以通过try-catch去捕获异常,而在Lambda表达式中声明throw(),是指示编译器这个函数不会抛异常,会引起编译的警告。
然后,Lambda可以支持返回函数指针,或者说是嵌套一个Lambda表达式,比如:
int main()
{
using namespace std;
// The following lambda expression contains a nested lambda
// expression.
int m = [](int x)
{ return [](int y) { return y * 2; }(x) + 3; }(5);
// Print the result.
cout 《 m 《 endl;
复制代码
}
我们可以把 return [](int y) { return y * 2; }(x) 抽象成 f(x) 所以原函数就是return f(5)+3 就是2*5+3=13
加入函数指针之后,我们来看一看一个Lambda表达式可以写的多复杂,这是来自于MSDN的官方的例子。
// higher_order_lambda_expression.cpp
// compile with: /EHsc
#include <iostream>
#include <functional>
int main()
{
using namespace std;
// The following code declares a lambda expression that returns
// another lambda expression that adds two numbers.
// The returned lambda expression captures parameter x by value.
auto g = [](int x) -> function<int (int)>
{ return [=](int y) { return x + y; }; };
// The following code declares a lambda expression that takes another
// lambda expression as its argument.
// The lambda expression applies the argument z to the function f
// and adds 1.
auto h = [](const function<int (int)>& f, int z)
{ return f(z) + 1; };
// Call the lambda expression that is bound to h.
auto a = h(g(7), 8);
// Print the result.
cout 《 a 《 endl;
复制代码
}
结果很简单就是7+8+1=16 我通过代码帮大家展开一下:
auto g = [](int x) -> function<int (int)>
{ return [=](int y) { return x + y; }; };
auto h = [](const function<int (int)>& f, int z)
{ return f(z) + 1; };
auto a = h(g(7), 8);
// 解:
// 我们先看看g(7) 等于什么
// 我们把g的返回值 return [=](int y) { return x + y; }; 抽象成一个函数t(y)
// 那么g(x)返回的就t(y)
// 也就是g(7)=t(y) 这里g的参数和t的参数无关
// 那么 h(g(7), 8)=h(t(y), 8))
// 代入h的表达式,我们发现t(y)就是f(z)
// 代入的结果就是 return t(8)+1,再把g(7)代入就是7+8+1=16
复制代码
cout 《 a 《 endl;
最后,有人会很好奇foe_each为什么可以传入Lambda表达式
首先,我们看看for_each的展开
template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f)
{
for ( ; first!=last; ++first ) f(*first);
return f;
}
复制代码
//From: cplusplus./reference/algorithm/for_each/
当然这不是实际的代码,但是我们可以看到,调用的只是f()再传入迭代器的值,所以,我们在写for_each的Lambda表达式的时候,传入参数一定是和迭代器的类型是匹配的。
在没有Lambda表达式的时候,只要是能写成 f(*first)这样的东西传进来的都行,所以就会出现结构体重载()操作符,这样的奇葩
void myfunction (int i) {
cout 《 " " 《 i;
}
struct myclass {
void operator() (int i) {cout 《 " " 《 i;}
} myobject;
int main () {
vector<int> myvector;
myvector.push_back(10);
myvector.push_back(20);
myvector.push_back(30);
cout 《 "myvector contains:";
for_each (myvector.begin(), myvector.end(), myfunction);
// or:
cout 《 "\nmyvector contains:";
for_each (myvector.begin(), myvector.end(), myobject);
cout 《 endl;
return 0;
复制代码
}
在C++(www.cppentry.com)中Lambda表达式被设计的相对复杂,但我相信,这也是C++(www.cppentry.com)这门语言的魅力所在,功能很强大,但是很难学。