1.说明
ambda表达式是C++11引入的一个重要特性之一,利用Lambda表达式,可以方便的定义和创建匿名函数。
Lambda表达式完整的声明格式如下:
[capture list] (params list) mutable exception-> return type { function body }
各项具体含义如下:
- capture list:捕获外部变量列表
- params list:形参列表
- mutable指示符:用来说用是否可以修改捕获的变量
- exception:异常设定
- return type:返回类型
- function body:函数体
2.注意细节
- 与普通函数不同,lambda表达式的参数列表不能有默认值;
- lambda可以省略参数列表和返回类型(默认返回void),但是必须包含捕获列表和函数体;
- 默认情况下,如果一个lambda中包含一个return之外的任何语句,编译器将假定此lambda的返回void;
- lambda若有返回类型,只能通过尾置返回的方法指定返回类型;
- 捕获列表只用于局部非static变量,lambda表达式可以直接使用局部static变量和它所在函数之外声明的名字;
3.使用
Lambda.h
// std::lambda [](){} lambda表达式 匿名函数
// [1] (2) mutable3 throw()4 ->int5 {6} 可嵌套
// 1. 捕获值列表(一种是按值捕获=,一种是按引用捕获&) 在此作用域可以访问的值,包括这个作用域里面的临时变量,类的可访问成员,全局变量
// 2. 是传入参数列表
// 3. 可修改标示符 mutable exception attribute(选填)
// 4. 错误抛出标示符,
// 5. 函数返回值 如果返回值唯一的话,我们可以省略 -> + 返回值类型
// 6. 是函数体
class CLambda
{
public:
CLambda() {}
virtual ~CLambda() {}
virtual void Run();
int Func(int x, int y) {}
private:
int m_Age = 0;
std::vector<int> m_vec = {1, 2, 3, 4, 5};
};
Lambda.cpp
#include "stdafx.h"
#include "Function.h"
#include <algorithm>
#include <map>
#include <iostream>
#include <thread>
// Lambda使用
void CLambda::Run()
{
printf("========std::lambda==========\n");
// eg:1
int nVal = 100;
auto f1 = [](int x, int y)
{
printf("[std::lambda] ::f1 x + y = %d\n", x + y);
return x + y;
};
int nR1 = f1(3, 4);
std::function<int(int, int)> f2 = [=, &nVal](int x, int y)
{
nVal = x + y;
m_Age = x + y;
printf("[std::lambda] ::f2 x + y = %d, Age = %d\n", x + y, m_Age);
return x + y;
};
f2(20, 4);
int nRes = [](int x, int y) -> int
{
return x + y;
}(5, 4);
printf("[std::lambda] nRes = %d\n", nRes);
// for_each 捕获值列表[this]中的this是用来指向这个类的,但[this]只有在类的内部,或者是this指针存在的情况下才能使用
(void)for_each(m_vec.begin(), m_vec.end(), [this](auto& n) //加引用和不加引用的区别
{
n += m_Age;
printf("[std::lambda] ::for_each n = %d\n", n);
});
auto fun = [](int& n)->void
{
printf("[std::lambda] ::for_each fun = %d\n", n);
};
(void)for_each(m_vec.begin(), m_vec.end(), fun); // lambda表达式作为参数
// eg:3 捕获当前类中的this指针,让lambda表达式拥有和当前类成员函数同样的访问权限
auto it = std::find_if(m_vec.begin(), m_vec.end(), [this](int ele) ->bool
{
return ele >= m_Age;
});
printf("[std::lambda] it = %d\n", *it);
}
调用:main.cpp
// C++11Demo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <time.h>
#include <thread>
#include "Lambda.h"
#include <iomanip>
#include <iostream>
#pragma warning( disable : 4996 )
/*
1. X宏
2. std::function
3. std::bind
4. std::for_each
5. Lambda表达式
6. std::atomic
7. auto
8. std::thread
9. 模板
*/
#define Tab printf("\n");
int main()
{
std::shared_ptr<CBase> pLambda = std::make_shared<CLambda>();
pLambda->Run(); Tab;
return 0;
}
运行结果: