当前位置: 首页 > article >正文

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

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

namespace {
struct Foo {
	int x{ 1 };

	void print()
	{
		//auto change1 = [=] { // bad
		auto change1 = [=, this] { // good, this: reference
			this->x = 11;
		};

		change1();
		std::cout << "x: " << x << std::endl; // x: 11

		auto change2 = [=, *this] { // *this: value
			//this->x = 22; // error C3490: 由于正在通过常量对象访问"x",因此无法对其进行修改
			auto m = this->x;
			std::cout << "x: " << x << std::endl; // x: 11
		};

		change2();
	}
};

} // namesapce

int test_lambda_20_this()
{
	Foo foo;
	std::cout << "x: " << foo.x << std::endl; // x: 1
	foo.print();
	std::cout << "x: " << foo.x << std::endl; // x: 11

	return 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: 3
	std::cout << "value: " << func(std::string{ "hello " }, std::string{ "world" }) << std::endl; // value: hello world

	return 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
		// ...
	};
}

} // namesapce

int 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


http://www.kler.cn/news/293936.html

相关文章:

  • halcon图像怎么显示在我们指定的区域
  • 【项目二】C++高性能服务器开发——日志系统(各种适配器)
  • Svn常用操作技巧详细说明
  • iptables防火墙的通俗理解,和k8s中的iptables策略使用
  • 数据结构基础之《(3)—二分法》
  • mysql高级sql
  • RAG与LLM原理及实践(14)---RAG Python 前端构建技术Flask
  • 『功能项目』Unity连接读取本地数据库【28】
  • Xcode打包出现错误Command PhaseScriptExecution failed with a nonzero exit code
  • 前端***
  • 使用Python读取Excel数据的详细指南
  • mhtml图片提取 百度图片下载
  • 使用html+css+layui实现动态表格组件
  • MySQL报错:[Err] 1075 - Incorrect table definitionmysql
  • 提高开发效率的实用工具库VueUse
  • 【2024数模国赛赛题思路公开】国赛D题思路丨附可运行代码丨无偿自提
  • 数据仓库: 6- 数据仓库分层
  • AI模块在人工智能中扮演着什么样的角色
  • 【机器学习】朴素贝叶斯方法的概率图表示以及贝叶斯统计中的共轭先验方法
  • idea中配置Translation插件完成翻译功能
  • 视觉语言模型(VLMs)知多少?
  • C#基础(6)值类型和引用类型
  • 7.统一网关-Gateway
  • 前端跨域问题详解与解决方案指南
  • ArcGIS Pro SDK (十三)地图创作 3 特殊图层
  • 【优化】Nginx 配置页面请求不走缓存 浏览器页面禁用缓存
  • 深入探讨Go语言中的切片与数组操作
  • Mysql在线安全变更工具 gh-ost
  • iOS——持久化
  • adb devices找不到设备