Created
February 14, 2018 09:13
-
-
Save Manu343726/e2527d755710f2fa342c15cceef6a6c0 to your computer and use it in GitHub Desktop.
Generic QRunnable implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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