如何在Lambda本身中获取C ++ Lambda函数的地址? [英] How to get the address of a C++ lambda function within the lambda itself?

查看:133
本文介绍了如何在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函数的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆