Is it possible to obtain a C style function pointer of a capturing lambda using static local variables?
I am trying to bind the first the argument of the derived function to the original
parameter
template <typename F>
class entry_hook
{
public:
entry_hook(void* original, F&& hook)
{
static auto bound = [&](auto&&... args)
{
return hook(original, std::forward<decltype(args)>(args)...);
};
auto* function_ptr = +[](auto&&... args) // -> decltype(bound(std::forward<decltype(args)>(args)...))
{
return bound(std::forward<decltype(args)>(args)...);
};
}
};
Using:
const auto hook = entry_hook(nullptr, [](void* original)
{
// ...
});
Fails to compile - unable to convert closure to function pointer
Removing the parameter pack from the wrapping lambda (by changing the following lines):
auto* function_ptr = +[](auto&&... args)
toauto* function_ptr = +[]()
return bound(std::forward<decltype(args)>(args)...);
toreturn bound();
Succesfully compiles and runs, although I would have assumed that by using a parameter pack that can be inferred at compile time on a lambda, wouldn't result in that lambda becoming a closure as such (being unconvertable to a function pointer as it requires a context)
I'm ideally trying to achieve:
const auto hook = entry_hook(nullptr, [](auto original, int param1, double param2)
{
// ...
});
Where original
is of type void(*)(int, double)
and entry_hook
can expose a function pointer to the passed in lambda
Reference:
This answer converts a capturing lambda into a function pointer C++ lambda with captures as a function pointer
This answer converts a lambda into a function pointer Obtaining function pointer to lambda?