Lambda作为函数参数

编程入门 行业动态 更新时间:2024-10-27 06:22:19
本文介绍了Lambda作为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在不使用 auto 或模板的情况下声明lambda变量或函数参数的符号是​​什么?有什么办法吗?或者编译器是否为编译器为程序员未知的每个lambda定义了一个唯一的类对象?如果是,为什么?不能只是作为某种函数指针传递?

What's the notation for declaring a lambda variable, or function parameter, without the use of auto or templates? Is there any way to do so? Or does the compiler define a unique class object for each lambda whose name is unknown to the programmer before compile time? If so, why? Can't they just be passed as some sort of function pointer? It would be a major disappointment if that were not possible.

推荐答案

Lambdas可能持有状态(如从周围环境捕获的引用) ;如果它们不存在,它们可以存储在函数指针中。如果他们这样做,他们必须存储为一个函数对象(因为没有在函数指针中保存状态)。

Lambdas may hold state (like captured references from the surrounding context); if they don't, they can be stored in a function pointer. If they do, they have to be stored as a function object (because there is no where to keep state in a function pointer).

// No state, can be a function pointer: int (*func_pointer) (int) = [](int a) { return a; }; // One with state: int b = 3; std::function<int (int)> func_obj = [&](int a) { return a*b; };

更多推荐

Lambda作为函数参数

本文发布于:2023-11-28 09:23:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641834.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   Lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!