如何在Lambda本身中获取C ++ Lambda函数的地址?

编程入门 行业动态 更新时间:2024-10-28 14:22:58
本文介绍了如何在Lambda本身中获取C ++ Lambda函数的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试弄清楚如何在内部获取lambda函数的地址。以下是示例代码:

I'm trying to figure out how to get the address of a lambda function within itself. Here is a sample code:

[]() { std::cout << "Address of this lambda function is => " << ???? }();

我知道我可以捕获变量中的lambda并打印地址,但是我想这样做

I know that I can capture the lambda in a variable and print the address, but I want to do it in place when this anonymous function is executing.

有没有更简单的方法?

推荐答案

不可能直接实现。

但是,lambda捕获是类,对象的地址与其第一个成员的地址一致。因此,如果您按值捕获一个对象作为第一个捕获,则第一个捕获的地址对应于lambda对象的地址:

However, lambda captures are classes and the address of an object coincides with the address of its first member. Hence, if you capture one object by value as the first capture, the address of the first capture corresponds to the address of the lambda object:

int main() { int i = 0; auto f = [i]() { printf("%p\n", &i); }; f(); printf("%p\n", &f); }

输出:

0x7ffe8b80d820 0x7ffe8b80d820

或者,您可以创建一个装饰器设计模式 lambda,将引用传递给将lambda捕获到其调用运算符中:

Alternatively, you can create a decorator design pattern lambda that passes the reference to the lambda capture into its call operator:

template<class F> auto decorate(F f) { return [f](auto&&... args) mutable { f(f, std::forward<decltype(args)>(args)...); }; } int main() { auto f = decorate([](auto& that) { printf("%p\n", &that); }); f(); }

更多推荐

如何在Lambda本身中获取C ++ Lambda函数的地址?

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

发布评论

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

>www.elefans.com

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