当前位置: 首页> 文旅> 旅游 > C++20中lambda表达式新增加支持的features

C++20中lambda表达式新增加支持的features

时间:2025/7/13 6:17:17来源:https://blog.csdn.net/fengbingchun/article/details/141787122 浏览次数:0次

      1.弃用通过[=]隐式捕获this,应使用[=,this]或[=,*this]显示捕获

namespace {
struct Foo {int x{ 1 };void print(){//auto change1 = [=] { // badauto change1 = [=, this] { // good, this: referencethis->x = 11;};change1();std::cout << "x: " << x << std::endl; // x: 11auto change2 = [=, *this] { // *this: value//this->x = 22; // error C3490: 由于正在通过常量对象访问"x",因此无法对其进行修改auto m = this->x;std::cout << "x: " << x << std::endl; // x: 11};change2();}
};} // namesapceint test_lambda_20_this()
{Foo foo;std::cout << "x: " << foo.x << std::endl; // x: 1foo.print();std::cout << "x: " << foo.x << std::endl; // x: 11return 0;
}

      执行结果如下图所示:

      2.lambda表达式中支持使用模板语法

int test_lambda_20_template()
{auto func = []<typename T>(const T& x, const T& y) {return (x + y);};std::cout << "value: " << func(1, 2) << std::endl; // value: 3std::cout << "value: " << func(std::string{ "hello " }, std::string{ "world" }) << std::endl; // value: hello worldreturn 0;
}

      3.lambda中支持参数包(parameter pack):包括按值捕获参数包和按引用捕获参数包

namespace {
template <typename... Args>
auto func1(Args&&... args)
{return [...args = std::forward<Args>(args)] { // by value// ...};
}template <typename... Args>
auto func2(Args&&... args) {return [&...args = std::forward<Args>(args)] { // by reference// ...};
}} // namesapceint test_lambda_20_parameter_pack()
{auto print = [](auto&&... args) {((std::cout << args << ' '), ...);std::cout << std::endl;};print(6, 8, "hello, world");return 0;
}

      GitHub:https://github.com/fengbingchun/Messy_Test

关键字:C++20中lambda表达式新增加支持的features

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: