Considering the following code (see https://rextester.com/OAWUM62639):
#include <iostream>
#include <functional>
void foo( int x_ )
{
std::cout<< "Value: " << x_ << "\n";
}
void something( void *c )
{
auto *f = static_cast<std::function<void()>*>(c);
(*f)();
}
int main()
{
int x = 2;
std::function<void()> lmbd = [=](){ foo(x); }; // lambda with capture.
something( &lmbd ); // is this implicit conversion safe?
}
Is the implicit conversion from a std::function<void()> to a void* safe?
The code seems to be running as expected, but I am not sure about the underlying rules that the C++11 standard imposes in such situations.
A similar question is this one here: How do I pass a std::function object to a function taking a function pointer?, but the accepted answer suggests using a reinterpret_cast. Is the reinterpret_cast a necessity in this case (see https://rextester.com/ZUY69757)?
std::function<void()> *to avoid *, and yes, it is safe. Also accepted answer in related question correctly states that it is not possible to pass::std::functioninstead of pointer to function.void*in C++ is definitely not good practice and in this case not safe because the lambda isn't a (function) pointer but an objectsomething()as a C-style function pointer. But you are not doing that, so the issue is moot. You are wrapping the lambda inside of astd::functionobject, and then passing an object pointer tosomething(). ANY object pointer can safely be converted to avoid*and then back to the original object.void*tostd::function*? Dou you mean C++ function with C-linkage?