C++11:lambda表达式基本语法

C++11:lambda表达式基本语法
#include <iostream>


int tmp = 0;

class Test
{
public:
	int i = 0;
	void func()
	{
		int a = 10;
		//错误,[]为空,没有捕获任何变量
		//auto f1 = []() {std::cout << i << std::endl; };

		auto f1 = [=]()
		{
			std::cout << i << std::endl;
			std::cout << tmp << std::endl;
		};

		auto f2 = [&]() { std::cout << i << std::endl; };

		//只是捕获类成员变量、全局变量,不能捕获局部变量
		auto f3 = [this]()
		{
			std::cout << i << std::endl;
			std::cout << tmp << std::endl;
			//std::cout << a << std::endl;
		};
	}
};


int main()
{
	int a = 0;
	int b = 0;
	auto f1 = []() {};
	//a, b以传值传递方式 
	auto f2 = [a, b]() { std::cout << a << ", " << b << std::endl; };
	auto f3 = [a, b](int x, int y)
	{
		std::cout << a << ", " << b << std::endl; 
		std::cout << x << ", " << y << std::endl;
	};

	//以值传递方式传给lambda表达式
	auto f4 = [=] { std::cout << a << ", " << b << std::endl; };

	//以引用方式捕获外部的变量
	auto f5 = [&] { std::cout << a << ", " << b << std::endl; };
	
	//a以值传递,其他以引用方式传递
	auto f6 = [&, a] { std::cout << a << ", " << b << std::endl; };
	
	//a以引用传递,其他值传递
	auto f7 = [=, &a] { std::cout << a << ", " << b << std::endl; };

	auto f8 = [&]() mutable
	{
		++a;
		std::cout << tmp << std::endl;
	};
	f8();
	std::cout << a << std::endl;


	system("pause");
	return 0;
}