Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mpenick/19c6407306b34f29eb47928521dcffee to your computer and use it in GitHub Desktop.
Save mpenick/19c6407306b34f29eb47928521dcffee to your computer and use it in GitHub Desktop.
#include <iostream>
#include <memory>
#include <tuple>
class Allocated {};
class Callback : public Allocated {
public:
virtual ~Callback() {}
virtual void run() = 0;
};
template <class F, class... Args>
class LambdaCallback : public Callback {
public:
LambdaCallback(F&& func, std::tuple<Args...>&& args)
: func_(std::move(func))
, args_(std::move(args)) {}
void run() {
std::apply(func_, args_); // C++17 convenience function, but can be done in C++11
}
private:
F func_;
std::tuple<Args...> args_;
};
template <class... Args>
void do_callback_internal(std::unique_ptr<Callback> callback) {
callback->run();
}
template <class F, class... Args>
void do_callback(F&& func, Args&&... args) {
do_callback_internal(std::make_unique<LambdaCallback<F, Args...>>(std::forward<F>(func), std::forward_as_tuple(std::move(args)...)));
}
int main() {
do_callback([](std::string s) {
std::cout << s << "\n";
}, "hello!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment