可调用对象

#include <iostream>
#include <functional>

using namespace std;

/*
* 1. 函数
* 2. 仿函数
* 3. lambda
*/

void test() {
	cout << "hello world" << endl;
}

//函数对象类型
using pf_type = void(*)();

void myfun(pf_type fun) {
	fun();
}

//仿函数,类对象可以调用()运算符,像函数一样
class Test {
public:
	void operator()() {
		cout << "world hello" << endl;
	}
};

//使用function
using pf_type1 = function<void()>;
void myfun1(pf_type1 fun) {
	fun();
}

int main() {
	//函数对象
	myfun(test);

	//仿函数
	Test t;
	t();

	//[]()->{}
	//[]为捕获列表,使用前文的变量, []不捕获,[=]值捕获所有变量,[&]引用捕获所有变量,[i]值捕获i,[&i],[=, &i],[&, i]
	int i = 10;
	[&i] {
		cout << i << endl;
		i = 20;
	}();
	cout << i << endl;

	//()lambda的参数
	[](int i) {
		cout << i << endl;
	}(5);

	//->,返回值类型,不写也会自动推断
	auto ret = [](int i)->int {
		cout << i << endl;
		return i;
	}(6);
	cout << ret << endl;

	//作为函数参数是lambda最常见用法,但是普通的函数指针类型下,lambda的捕获列表不能捕获变量必须为空
	myfun([]() {
		cout << "lambda" << endl;
		});

	//myfun([i]() {
	//	cout << "lambda" << endl;
	//	cout << i << endl;
	//	});

	//使用funtional,则可以捕获
	myfun1([i]() {
		cout << "lambda" << endl;
		cout << i << endl;
	});

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值