How to explicitly capture a macro inside a lambda capture?

Viewed 309

I have a lambda and want to print the name of the function the lambda is defined in. If I use __FUNCTION__ inside the lambda, it'll just print operator(), which is reasonable since that's the function the macro is in.

However, Clang-Tidy warns about this and mentions the following:

Clang-Tidy: Inside a lambda, '__FUNCTION__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly

Is there any way I can capture the name of the enclosing function without declaring it before the lambda with const char* name = __FUNCTION__ and capture name. I.e. something like this:

#include <iostream>

int main()
{
    [&__FUNCTION__](){
        std::cout << __FUNCTION__ << std::endl;  // Should print "main".
    }();

    return 0;
}

The code above obviously won't work as the macro will expand in the preprocessing stage.

The reason for the restriction is because everything is inside a macro that's going to be used in an expression, but I still want to run some statements. For example:

#define ALLOCATE(allocator, size) [&](){                                            \
    std::cout << "Allocating in " << __FILE__ << ":" << __FUNCTION__ << std::endl;  \        
    return allocator.allocate(size);                                                \
}()
1 Answers

Yes, since C++14 it's possible to use lambda capture initializers which allows arbitrary expressions to be captured by name. So a solution is:

#include <iostream>

int main()
{
    [function_name=__FUNCTION__](){
        std::cout << function_name << std::endl;  // Prints "main".
    }();

    return 0;
}
Related