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 => " << ????
}();
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.
Is there a simpler way to do so?
Capture the lambda:
It is not directly possible.
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:
Outputs:
Alternatively, you can create a decorator design pattern lambda that passes the reference to the lambda capture into its call operator:
One way to solve this, would be to replace the lambda with a hand written functor class. It's also what the lambda essentially is under the hood.
Then you can get the address through
this
, even without ever assigning the functor to a variable:This has the advantage that this is 100% portable, and extremely easy to reason about and understand.
There is no way to directly get the address of a lambda object within a lambda.
Now, as it happens this is quite often useful. The most common use is in order to recurse.
The
y_combinator
comes from languages where you could not talk about yourself until you where defined. It can be implemented pretty easily in c++:now you can do this:
A variations of this can include:
where the
self
passed can be called without passing inself
as the first argument.The second matches the real y combinator (aka the fixed point combinator) I believe. Which you want depends on what you mean by 'address of lambda'.
It is possible but highly depends on the platform and compiler optimization.
On most of the architectures I know, there is register called instruction pointer. The point of this solution is to extract it when we are inside the function.
On amd64 Following code should give you addresses close to the function one.
But for example on gcc https://godbolt.org/z/dQXmHm with
-O3
optimization level function might be inlined.