#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;
}