qtqtconcurrentqfuture

How to create a QFuture with an immediately available value?


I have a function which returns QFuture object as a result of a QtConcurrent::run computation. However, there could be some conditions before running the concurrent method where I need to manually return a value-holding future from my function.

QFuture<bool> foo(const QString &bar)
{
    if (bar.isEmpty()) {
        return QFuture<bool>(false); // This does not work.
        // Here I need to return from the function, but I don't know how to do it.
    }
    return QtConcurrent::run([=]() -> bool {
        // Asynchronous computations...
    });
}

How to manually create the QFuture object?
Or (more globally) how to properly return from such method?


Solution

  • When there's no data to return, things are easy - this should be the first thing to try anyway in modern C++:

    return {};
    

    Or, if you're targeting some obsolete platform (<Qt 5.6):

    return QFuture<bool>();
    

    That way you get an invalid future. There's no way to directly create a future that carries preset data, you'd have to use QFutureInterface for that:

    // https://github.com/KubaO/stackoverflown/tree/master/questions/qfuture-immediate-50772976
    #include <QtConcurrent>
    
    template <typename T> QFuture<T> finishedFuture(const T &val) {
       QFutureInterface<T> fi;
       fi.reportFinished(&val);
       return QFuture<T>(&fi);
    }
    
    QFuture<bool> foo(bool val, bool valid) {
       if (!valid)
          return {};
       return finishedFuture(val);
    }
    
    int main() {
       Q_ASSERT(foo(true, true));
       Q_ASSERT(!foo(false, true));
       Q_ASSERT(foo(false, false).isCanceled());
       Q_ASSERT(foo(true, false).isCanceled());
    }