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

C++ 里面lambda和函数指针的转换

问题说明

原始问题,代码如下会编译报错:

using DecisionFn = bool(*)();class Decide
{
public:Decide(DecisionFn dec) : _dec{dec} {}
private:DecisionFn _dec;
};int main()
{int x = 5;Decide greaterThanThree{ [x](){ return x > 3; } };return 0;
}

原因分析

lambda表达式转成函数指针,当lambda没有捕获变量的时候,可以隐式转为指针函数

§ 5.1.2 The closure type for a lambda-expression with no
lambda-capture
has a public non-virtual non-explicit const conversion
function to pointer to function
having the same parameter and return
types as the closure type’s function call operator. The value returned
by this conversion function shall be the address of a function that,
when invoked, has the same effect as invoking the closure type’s
function call operator.

解决方案

当包含有捕获变量的时候,可以使用如下方式

  1. 把捕获的变量作为参数来传递
typedef bool(*DecisionFn)(int);Decide greaterThanThree{ []( int x ){ return x > 3; } };Decide greaterThanThree {(x > 3) ? [](){ return true; } : [](){ return false; }};
  1. 使用std::function来替代原始指针
using DecisionFn = std::function<bool()>;Decide greaterThanThree { [x](){ return x > 3; } };

参考:

https://stackoverflow.com/questions/7852101/c-lambda-with-captures-as-a-function-pointer
https://stackoverflow.com/questions/28746744/passing-capturing-lambda-as-function-pointer

http://www.lryc.cn/news/90816.html

相关文章:

  • 前端Rust开发WebAssembly与Swc插件快速入门
  • 【C++ 学习 ⑧】- STL 简介
  • 论文笔记--Deep contextualized word representations
  • 【MySQL高级篇笔记-性能分析工具的使用 (中) 】
  • 大学生数学建模题论文
  • 论文阅读 —— 滤波激光SLAM
  • JavaScript键盘事件
  • opengl灯光基础:2.1 光照基础知识
  • 大屏时代:引领信息可视化的新潮流
  • ChatGTP全景图 | 背景+技术篇
  • 计算机专业学习的核心是什么?
  • 基于springboot地方旅游系统的设计与实现
  • 一些学习资料链接
  • Webpack打包图片-JS-Vue
  • 进程控制(Linux)
  • C Primer Plus第十四章编程练习答案
  • 又名管道和无名管道
  • 操作系统复习4.1.0-文件管理结构
  • 【嵌入式烧录/刷写文件】-2.6-剪切/保留Intel Hex文件中指定地址范围内的数据
  • JavaScript表单事件(下篇)
  • 机器学习 | SVD奇异值分解
  • chatgpt赋能python:Python取值:介绍
  • 广播风暴的成因以及如何判断、解决
  • Loki 日志收集系统
  • uCOSii信号量的作用
  • Android 13 版本变更总览
  • QT 设计ROS GUI界面订阅和发布话题
  • pandas数据预处理
  • Jupyter Notebook如何导入导出文件
  • Linux:/dev/tty、/dev/tty0 和 /dev/console 之间的区别