Skip to content

Instantly share code, notes, and snippets.

@semmel
Last active January 14, 2017 20:33
Show Gist options
  • Save semmel/677e77f2849f7020f88bfa28aea694b0 to your computer and use it in GitHub Desktop.
Save semmel/677e77f2849f7020f88bfa28aea694b0 to your computer and use it in GitHub Desktop.
Convert a Lambda to std::function e.g. for currying
#include <iostream>
#include <functional>
#include <memory>
#include <iterator>
#include <algorithm>
using namespace std;
template<typename T>
struct memfun_type
{
using type = void;
};
template<typename Ret, typename Class, typename... Args>
struct memfun_type<Ret(Class::*)(Args...) const>
{
using type = std::function<Ret(Args...)>;
};
template<typename F>
typename memfun_type<decltype(&F::operator())>::type
FFL(F const &func)
{
// Function from lambda !
return func;
}
template <typename R, typename... Args>
void Callback(std::function<R(Args...)> f)
{
// store f and call later
std::cout << "invoking callback.." << endl;
cout << f(2, 3) << endl;
}
auto sub = FFL([](int a, int b)
{
return a - b;
});
class Person {
public:
std::string name;
Person(const char* szName) : name(szName) {}
void printName(){
std::cout << name << std::endl;
}
};
std::function<void()> printSomeName;
std::vector<int> v1 {1, 2, 5, 5, 5, 9};
std::vector<int> v2 {2, 5, 7};
std::vector<int> diff;
int main()
{
Callback(FFL([](int a, float b)
{
return a + b;
}));
std::cout << "3 - 10 = " << sub(3, 10) << std::endl;
Person p("A nice person");
printSomeName = std::bind(&Person::printName, p);
printSomeName();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment