我正在尝试弄清楚如何在内部获取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函数的地址?
发布评论