Reputation: 2694
How can we create a pointer in a c++ lambda capture list? For example, we can create an integer variable and make the lambda stateful:
auto lambda1 = [a = int{ 5 }]() mutable {
a = 3;
}
However, when we change a to a pointer, the compiler doesn't work:
auto lambda2 = [a = void* { nullptr }]() mutable {
a = ...;
}
Another workaround is to declare a pointer outside and then copy it, but this seems very redundant
void* a;
auto lambda3 = [a]() mutable {
a = ...
}
Upvotes: 2
Views: 221
Reputation: 32972
You can static_cast
the nullptr
to void*
auto lambda2 = [a = static_cast<void*>(nullptr)]() mutable {
// ..
};
That being said, it looks like you want to capture a pointer to some arbitrary types to the lambda. Shouldn't it be done by using templates? Maybe you want to have a look into the generic lambda or template parameter lists in lambda expressions
Thanks to @HolyBlackCat for pointing out for the fact, that the std::nullptr_t
will not work for the case
int x;
std::nullptr_t p = &x;// error: 'initializing': cannot convert from 'int *' to 'nullptr'
Therefore it can not be used for this case.
#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.
Upvotes: 3