Skip to content

Instantly share code, notes, and snippets.

@rmitton
Last active February 29, 2020 19:22
Show Gist options
  • Save rmitton/e5a4d7fea32e5d206b33dbe6bc239637 to your computer and use it in GitHub Desktop.
Save rmitton/e5a4d7fea32e5d206b33dbe6bc239637 to your computer and use it in GitHub Desktop.
Tiny std::function implementation
/* EDIT:
* For future reference, this code doesn't work right so don't use it.
* (but probably could be fixed with some care and attention)
*/
// Tiny std::function workalike, to allow storing lambdas with captures. (public domain)
template <typename> struct fnptr;
template <typename Ret, typename... Args> struct fnptr<Ret(Args...)> {
void *obj = nullptr;
Ret (*wrap)(void*, Args...) = nullptr;
fnptr() = default;
fnptr(Ret target(Args...)) : fnptr([=] (Args... args) { return target(args...); }) {}
template <typename T> fnptr(T&& fn) : obj(&fn), wrap([](void *fn, Args... args) { return (*(T *)fn)(args...); }) {}
Ret operator()(Args... args) const { return wrap(obj, args...); }
};
// Example:
//
// void hello() { printf("hello\n"); }
//
// fnptr<void()> x;
//
// int main() {
// int q=1;
// x = hello;
// x();
// x = [&q] { q++; printf("again\n"); };
// x();
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment