Manu343726
2/14/2018 - 9:13 AM

Generic QRunnable implementation

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();
});