AsyncProgressDialog
FunctionThread.h
1 #pragma once
2 
3 #include "TaskThread.h"
4 
5 #include <QThread>
6 #include <QVariant>
7 
8 #include <optional>
9 
10 namespace APD
11 {
12 
21 template <class ResultType>
22 class FunctionThread : public TaskThread
23 {
24 public:
26  using Function = std::function<ResultType(TaskThread*)>;
27 
33  FunctionThread(Function func, QObject* parent = nullptr)
34  : TaskThread(parent)
35  , m_func(std::move(func))
36  {}
37 
42  std::optional<ResultType> result() const
43  {
44  std::lock_guard<std::mutex> lck (m_resultMutex);
45  return m_result;
46  }
47 
48 protected:
49 
53  void run() override
54  {
55  auto result = m_func(this);
56  std::lock_guard<std::mutex> lck (m_resultMutex);
57  m_result = std::move(result);
58  }
59 
60 private:
61  Q_DISABLE_COPY(FunctionThread)
62 
63  Function m_func;
64  std::optional<ResultType> m_result;
65  mutable std::mutex m_resultMutex;
66 };
67 
72 template<>
73 class FunctionThread<void>
74  : public TaskThread
75 {
76 public:
78  using Function = std::function<void(TaskThread*)>;
79 
85  FunctionThread(Function func, QObject* parent = nullptr)
86  : TaskThread(parent)
87  , m_func(std::move(func))
88  {}
89 
90 protected:
94  void run() override
95  {
96  m_func(this);
97  }
98 
99 private:
100  Q_DISABLE_COPY(FunctionThread<void>)
101 
102  Function m_func;
103 };
104 
105 
106 };
std::optional< ResultType > result() const
Definition: FunctionThread.h:42
std::function< void(TaskThread *)> Function
Definition of a function to be passed to constructor of this class.
Definition: FunctionThread.h:78
void run() override
Definition: FunctionThread.h:94
FunctionThread(Function func, QObject *parent=nullptr)
Definition: FunctionThread.h:33
FunctionThread(Function func, QObject *parent=nullptr)
Definition: FunctionThread.h:85
Base class for all threads capable of reporting progress and cancelling the progress when requested.
Definition: TaskThread.h:11
void run() override
Definition: FunctionThread.h:53
std::function< ResultType(TaskThread *)> Function
Definition of a function to be passed to constructor of this class.
Definition: FunctionThread.h:26
A thread class, which executes the function provided in the constructor of this class as soon as the ...
Definition: FunctionThread.h:22
A thread class, which executes the function provided in the constructor of this class as soon as the ...
Definition: FunctionThread.h:73