Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.
Consider the follo
A simular answer but i made it so you don't have to specify the type of returned pointer (note that the generic version requires C++20):
#include
template
struct function_traits;
template
struct function_traits {
typedef Ret(*ptr)(Args...);
};
template
struct function_traits : function_traits {};
template
struct function_traits : function_traits {};
using voidfun = void(*)();
template
voidfun lambda_to_void_function(F lambda) {
static auto lambda_copy = lambda;
return []() {
lambda_copy();
};
}
// requires C++20
template
auto lambda_to_pointer(F lambda) -> typename function_traits::ptr {
static auto lambda_copy = lambda;
return [](Args... args) {
return lambda_copy(args...);
};
}
int main() {
int num;
void(*foo)() = lambda_to_void_function([&num]() {
num = 1234;
});
foo();
std::cout << num << std::endl; // 1234
int(*bar)(int) = lambda_to_pointer([&](int a) -> int {
num = a;
return a;
});
std::cout << bar(4321) << std::endl; // 4321
std::cout << num << std::endl; // 4321
}