-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqcfuture.h
109 lines (85 loc) · 2.95 KB
/
qcfuture.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#ifndef QCFUTURE_H
#define QCFUTURE_H
#include <QFuture>
#include <QObject>
namespace QCFuture
{
namespace Private {
template <typename T>
class Invoker {
public:
template <typename F>
static void voidInvoke(QFuture<T> future, F f) {
f(future.result());
}
template <typename R, typename F>
static R invoke(QFuture<T> future, F f) {
return f(future.result());
}
};
template <>
class Invoker<void> {
public:
template <typename F>
static void voidInvoke(QFuture<void> future, F f) {
Q_UNUSED(future);
f();
}
template <typename R, typename F>
static R invoke(QFuture<void> future, F f) {
Q_UNUSED(future);
return f();
}
};
template <typename R>
class Delegate {
public:
template <typename T, typename F, typename D>
static void call(QFuture<T> future,F f, D defer) {
R r = Invoker<T>::template invoke<R>(future, f);
defer->reportResult(r);
}
};
template <>
class Delegate<void> {
public:
template<typename T, typename F, typename D>
static void call(QFuture<T> future, F f, D defer) {
Q_UNUSED(defer);
Invoker<T>::voidInvoke(future, f);
}
};
}
template <typename T>
class Defer : public QObject, public QFutureInterface<T>{
public:
inline Defer(QObject* parent = 0): QObject(parent) {}
};
template <typename F>
auto subscribe(QFuture<void> future, F func, QObject* context) -> QFuture<decltype(func())>{
auto *defer = new Defer<decltype(func())> (context);
QFutureWatcher<void> *watcher = new QFutureWatcher<void>(context);
watcher->setFuture(future);
QObject::connect(watcher, &QFutureWatcher<void>::finished,[=](){
Private::Delegate<decltype(func())>::call(future, func, defer);
defer->reportFinished();
watcher->deleteLater();
defer->deleteLater();
});
return defer->future();
}
template <typename T,typename F>
auto subscribe(QFuture<T> future, F func, QObject* context) -> QFuture<decltype(func(future.result()))> {
auto *defer = new Defer<decltype(func(future.result()))> (context);
QFutureWatcher<T> *watcher = new QFutureWatcher<T>(context);
watcher->setFuture(future);
QObject::connect(watcher, &QFutureWatcher<T>::finished,[=](){
Private::Delegate<decltype(func(future.result()))>::call(future, func, defer);
defer->reportFinished();
watcher->deleteLater();
defer->deleteLater();
});
return defer->future();
}
}
#endif // QCFUTURE_H