<分区>
我有一个 lambda,我想打印定义 lambda 的函数的名称。如果我在 lambda 中使用 __FUNCTION__
,它只会打印 operator()
,这是合理的,因为这是宏所在的函数。
但是,Clang-Tidy 对此发出警告并提到以下内容:
Clang-Tidy: Inside a lambda, '__FUNCTION__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly
有什么方法可以捕获封闭函数的名称而无需在 lambda 之前用 const char* name = __FUNCTION__
声明它并捕获 name
。 IE。像这样:
#include <iostream>
int main()
{
[&__FUNCTION__](){
std::cout << __FUNCTION__ << std::endl; // Should print "main".
}();
return 0;
}
上面的代码显然不会工作,因为宏会在预处理阶段展开。
限制的原因是因为一切都在将在表达式中使用的宏中,但我仍然想运行一些语句。例如:
#define ALLOCATE(allocator, size) [&](){ \
std::cout << "Allocating in " << __FILE__ << ":" << __FUNCTION__ << std::endl; \
return allocator.allocate(size); \
}()