分类: C/C++
2021-02-19 14:13:39
闭包就是能够读取其他函数内部变量的函数。
在很多编程语言中都有闭包的概念,譬如:python,js,lua等等
def outer_func():
inner_value = 10
def inner_func(name):
print(inner_value)
print(name)
return inner_func
f = outer_func()
f("Hello")
上面的outer_func 返回一个函数,而返回的函数拥有了状态,这个状态是outer_func里面的对象。
发现c++实现闭包有两种方式
void foo(int a, int b)
{
cout << "a: " << a << endl;
cout << "b: " << b << endl;
}
void foo1(int a, int b, int c)
{
cout << "a: " << a << endl;
cout << "b: " << b << endl;
cout << "c: " << c << endl;
}
int main()
{
auto f1 = std::bind(foo, std::placeholders::_1, 10);
f1(100);
// f2可以保存各种状态,callable的object的参数格式和function参数格式一致即可。
std::function f2;
f2 = std::bind(foo, std::placeholders::_1, 20);
f2(100);
f2 = std::bind(foo, std::placeholders::_1, 30);
f2(100);
// ===============
f2 = std::bind(foo1, std::placeholders::_1, 10, 20);
f2(100);
}
std::function + lambda 的实现方式
void foo(int a, int b)
{
cout << "a: " << a << endl;
cout << "b: " << b << endl;
}
void foo1(int a, int b, int c)
{
cout << "a: " << a << endl;
cout << "b: " << b << endl;
cout << "c: " << c << endl;
}
int main()
{
auto f1 = [](int x) {
foo(x, 20);
};
f1(100);
auto f2 = [](int x) {
foo1(x, 20, 30);
};
f2(200);
}
如果有需要,lambda需要通过copy value的方式把值传递进去给lambda函数,如果要传递的对象过大,则使用shared_ptr进行优化