#include <iostream>
#include <memory>
#include <utility>
//值捕获
void lambda_value_capture()
{
int value = 1;
auto copy_value = [value] {
return value;
};
value = 100;
auto stored_value = copy_value();
std::cout << "stored_value =" << stored_value << std::endl;
}
//引用捕获
void lambda_reference_capture()
{
int value = 1;
auto copy_value = [&value] {
return value;
};
value = 100;
auto stored_value = copy_value();
std::cout << "stored_value =" << stored_value << std::endl;
}
//表达式捕获
void lambda_expression_capture()
{
auto important = std::make_unique<int>(1);
auto add = [v1 = 1, v2 = std::move(important)](int x, int y)->int{
return x + y + v1 + (*v2);
};
std::cout << add(3, 4) << std::endl;
}
//泛型lambda
auto add = [](auto x, auto y)
{
return x + y;
};
int main()
{
lambda_value_capture();
lambda_reference_capture();
lambda_expression_capture();
std::cout << add(1, 2) << std::endl;
std::cout << add(1.1, 2.2) << std::endl;
return 0;
}
lambda的用法
最新推荐文章于 2024-11-05 17:16:24 发布