diff --git a/src/blackmisc/worker.cpp b/src/blackmisc/worker.cpp index fc9872ab0..3c16ba52b 100644 --- a/src/blackmisc/worker.cpp +++ b/src/blackmisc/worker.cpp @@ -13,11 +13,13 @@ namespace BlackMisc { - CWorker *CWorker::fromTaskImpl(QObject *owner, const QString &name, std::function task) + CWorker *CWorker::fromTaskImpl(QObject *owner, const QString &name, int typeId, std::function task) { auto *thread = new CRegularThread(owner); auto *worker = new CWorker(task); + if (typeId != QMetaType::Void) { worker->m_result = CVariant(typeId, nullptr); } + QString ownerName = owner->objectName().isEmpty() ? owner->metaObject()->className() : owner->objectName(); thread->setObjectName(ownerName + ":" + name); worker->setObjectName(name); diff --git a/src/blackmisc/worker.h b/src/blackmisc/worker.h index aea996c68..744460f92 100644 --- a/src/blackmisc/worker.h +++ b/src/blackmisc/worker.h @@ -213,20 +213,29 @@ namespace BlackMisc template static CWorker *fromTask(QObject *owner, const QString &name, F task) { - return fromTaskImpl(owner, name, [task]() { return CVariant::fromResultOf(task); }); + int typeId = qMetaTypeId::type>(); + return fromTaskImpl(owner, name, typeId, [task]() { return CVariant::fromResultOf(task); }); } //! Connects to a functor to which will be passed the result when the task is finished. //! \tparam R The return type of the task. //! \threadsafe template - void thenWithResult(F functor) { then([this, functor]() { functor(this->result()); }); } + void thenWithResult(F functor) + { + Q_ASSERT_X(m_result.canConvert(), Q_FUNC_INFO, "Type in thenWithResult must match return type of task"); + then([this, functor]() { functor(this->result()); }); + } //! Connects to a functor or method to which will be passed the result when the task is finished. //! \tparam R The return type of the task. //! \threadsafe template - void thenWithResult(T *context, F functor) { then(context, [this, context, functor]() { invoke(context, functor, this->result()); }); } + void thenWithResult(T *context, F functor) + { + Q_ASSERT_X(m_result.canConvert(), Q_FUNC_INFO, "Type in thenWithResult must match return type of task"); + then(context, [this, context, functor]() { invoke(context, functor, this->result()); }); + } //! Returns the result of the task, waiting for it to finish if necessary. //! \tparam R The return type of the task. @@ -240,7 +249,7 @@ namespace BlackMisc private: CWorker(std::function task) : m_task(task) {} - static CWorker *fromTaskImpl(QObject *owner, const QString &name, std::function task); + static CWorker *fromTaskImpl(QObject *owner, const QString &name, int typeId, std::function task); std::function m_task; CVariant m_result;