Skip to content

Instantly share code, notes, and snippets.

@jarekdziedzic
Last active November 10, 2015 11:37
Show Gist options
  • Save jarekdziedzic/039e7e4bcbb31d0a4cbd to your computer and use it in GitHub Desktop.
Save jarekdziedzic/039e7e4bcbb31d0a4cbd to your computer and use it in GitHub Desktop.
Lambda std function witchcraft
#include <iostream>
#include <functional>
using namespace std;
template<typename T> struct memfn_ptr_to_fn_ptr { };
template<typename C, typename R, typename... A>
struct memfn_ptr_to_fn_ptr<R(C::*)(A...)> { using type = R(A...); };
template<typename C, typename R, typename... A>
struct memfn_ptr_to_fn_ptr<R(C::*)(A...) const> { using type = R(A...); };
template<typename L>
struct get_lambda_signature
{
using type = typename memfn_ptr_to_fn_ptr<decltype(&L::operator())>::type;
};
template<typename L>
auto to_function(L lambda) -> std::function<typename get_lambda_signature<L>::type>
{
return lambda;
}
template <typename T>
class TypePrinter;
int main(int argc, char** argv)
{
int x = 2;
auto f = [&x](int param) { return x*param;};
auto f2 = [&x]() { return x;};
auto f3 = [x](int param) mutable { return ++x*param;};
auto f4 = [](int param) { return ++param;};
auto f5 = [](int param) { ++param;};
auto f6 = [](){};
auto func = to_function(f);
auto func2 = to_function(f2);
auto func3 = to_function(f3);
auto func4 = to_function(f4);
auto func5 = to_function(f5);
auto func6 = to_function(f6);
// TypePrinter<decltype(func6)>();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment