I have the following code that can convert a lambda into a C-style function pointer. This works for all lambdas including lambdas with captures.
#include <iostream>
#include <type_traits>
#include <utility>
template <typename Lambda>
struct lambda_traits : lambda_traits<decltype(&Lambda::operator())>
{};
template <typename Lambda, typename Return, typename... Args>
struct lambda_traits<Return(Lambda::*)(Args...)> : lambda_traits<Return(Lambda::*)(Args...) const>
{};
template <typename Lambda, typename Return, typename... Args>
struct lambda_traits<Return(Lambda::*)(Args...) const>
{
using pointer = typename std::add_pointer<Return(Args...)>::type;
static pointer to_pointer(Lambda&& lambda)
{
static Lambda static_lambda = std::forward<Lambda>(lambda);
return [](Args... args){
return static_lambda(std::forward<Args>(args)...);
};
}
};
template <typename Lambda>
inline typename lambda_traits<Lambda>::pointer to_pointer(Lambda&& lambda)
{
return lambda_traits<Lambda>::to_pointer(std::forward<Lambda>(lambda));
}
This can be used as follows to pass a lambda with a capture into a C-style API:
// Function that takes a C-style function pointer as an argument
void call_function(void(*function)())
{
(*function)();
}
int main()
{
int x = 42;
// Pass the lambda to the C-style API
// This works even though the lambda captures 'x'!
call_function(to_pointer([x] {
std::cout << x << std::endl;
}));
}
Given this, it seems like it should be relatively straightforward to write a similar template that can convert lambdas (including lambdas with captures) generically into std::function
objects, but I am struggling to figure out how. (I am not super familiar with template meta-programming techniques so I am a bit lost)
This is what I tried, but it fails to compile:
template <typename Lambda>
struct lambda_traits : lambda_traits<decltype(&Lambda::operator())>
{};
template <typename Lambda, typename Return, typename... Args>
struct lambda_traits<typename std::function<Return(Args...)>> : lambda_traits<typename std::function<Return(Args...)> const>
{};
template <typename Lambda, typename Return, typename... Args>
struct lambda_traits<typename std::function<Return(Args...)> const>
{
using pointer = typename std::function<Return(Args...)>*;
static pointer to_pointer(Lambda&& lambda)
{
static Lambda static_lambda = std::forward<Lambda>(lambda);
return [](Args... args) {
return static_lambda(std::forward<Args>(args)...);
};
}
};
template <typename Lambda>
inline typename lambda_traits<Lambda>::pointer to_pointer(Lambda&& lambda)
{
return lambda_traits<Lambda>::to_pointer(std::forward<Lambda>(lambda));
}
This fails to compile and says that the Lambda
template parameter is not being used by the partial specialization.
What is the correct way to do this?
(Note, I am stuck using a C++11 compatible compiler so features from C++14 and beyond are not available)
std::function(lambda)
(i.e. the class template argument deduction forstd::function
)? – Sarmentum