c++c++11lambdac++14c++17

How to get the address of a C++ lambda function within the lambda itself?


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?


Solution

  • 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:

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

    Outputs:

    0x7ffe8b80d820
    0x7ffe8b80d820
    

    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();
    }