Skip to content

Instantly share code, notes, and snippets.

@moleike
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moleike/b010d6a40dfa544bf5d3 to your computer and use it in GitHub Desktop.
Save moleike/b010d6a40dfa544bf5d3 to your computer and use it in GitHub Desktop.
// credit to http://stackoverflow.com/a/14665230/339222
#include <functional>
#include <chrono>
#include <future>
#include <iostream>
class later
{
public:
template <class callable, class... arguments>
later(int after, bool async, callable&& f, arguments&&... args)
{
std::function<typename std::result_of<callable(arguments...)>::type()>
task(std::bind(std::forward<callable>(f),
std::forward<arguments>(args)...));
if (async) {
std::thread([after, task]() {
std::this_thread::sleep_for(
std::chrono::milliseconds(after)
);
task();
}).detach();
} else {
std::this_thread::sleep_for(
std::chrono::milliseconds(after)
);
task();
}
}
};
void test1(void)
{
return;
}
void test2(int a)
{
std::cout << a << std::endl;
return;
}
int main()
{
later later_test1(1000, false, &test1);
later later_test2(1000, false, &test2, 101);
later later_test3(1000, false, [](int a, int b) -> void {
std::cout << (a + b) << std::endl; }, 3, 4);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment