我们如何在c++中创建一个指针lambda 捕获列表?例如,我们可以创建一个整型变量并使 lambda 有状态:
auto lambda1 = [a = int{ 5 }]() mutable {
a = 3;
}
但是,当我们将 a 更改为指针时,编译器不起作用:
auto lambda2 = [a = void* { nullptr }]() mutable {
a = ...;
}
另一种解决方法是在外部声明一个指针,然后复制它,但这似乎非常多余
void* a;
auto lambda3 = [a]() mutable {
a = ...
}
最佳答案
您可以将 nullptr
static_cast
转换为 void*
auto lambda2 = [a = static_cast<void*>(nullptr)]() mutable {
// ..
};
话虽如此,您似乎想要捕获指向 lambda 的某些任意类型的指针。难道不应该用模板来完成吗?也许您想查看 generic lambda或template parameter lists in lambda expressions
感谢@HolyBlackCat指出这个事实,std::nullptr_t
不适用于这种情况
int x;
std::nullptr_t p = &x;// error: 'initializing': cannot convert from 'int *' to 'nullptr'
因此它不能用于这种情况。
<删除> 您可以按如下方式使用 std::nullptr_t#include <cstddef> // std::nullptr_t
auto lambda2 = [a = std::nullptr_t{}]() mutable {
// ...
};
std::nullptr_t
is the type of the null pointer literal,nullptr
. It is a distinct type that is not itself a pointer type or a pointer to member type. Its values are null pointer constants (seeNULL
), and may be implicitly converted to any pointer and pointer to member type.
关于c++ - 如何在 lambda 捕获列表中创建指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68716780/