Skip to content

Instantly share code, notes, and snippets.

@Manu343726
Created February 14, 2018 09:13
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 Manu343726/e2527d755710f2fa342c15cceef6a6c0 to your computer and use it in GitHub Desktop.
Save Manu343726/e2527d755710f2fa342c15cceef6a6c0 to your computer and use it in GitHub Desktop.
Generic QRunnable implementation
// Java sucks, and importing design patterns from Java sucks even more.
//
// This template avoids writing one QRunnable derived class per use case
// by wrapping any C++ callable.
template<typename Function>
struct Task : public QRunnable, Function
{
template<typename... Args>
Task(Args&&... args) :
Function{std::forward<Args>(args)...}
{}
void run() override final // Well, this is the only thing copyed from Java that makes sense
{
Function::function();
}
};
template<typename Function>
Task<typename std::decay<Function>::type>* makeTask(Function&& function)
{
return new Task<typename std::decay<Function>::type>{std::forward<Function>(function)};
}
// Posting an arbitrary task to a Qt thread pool never was this easy
QThreadPool::globalInstance()->start(makeTask([&std::cout]
{
std::cout << "Fuck you\n";
});
QThreadPool::globalInstance()->start(makeTask([this]
{
myMethod();
});
QThreadPool::globalInstance()->start(makeTask([businessOp]
{
businessOp.run();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment