我有以下内容:
QFutureWatcher<bool> *procwatcher;
procwatcher = new QFutureWatcher<bool>();
QFuture<bool> procfuture = QtConcurrent::run(this, &EraserBatch::processTile);
procwatcher->setFuture(procfuture);
QFutureWatcher<bool> *procwatcher2;
procwatcher2 = new QFutureWatcher<bool>();
QFuture<bool> procfuture2 = QtConcurrent::run(this, &EraserBatch::processTile);
procwatcher2->setFuture(procfuture2);
创建这两种类型的动态大小数组的语法是什么 - QFutureWatcher和QFuture,以便我可以说procwatcher [0]和procfuture [1]等。
谢谢!
答案 0 :(得分:5)
只要模板完全专业化(即指定了所有模板参数),您就可以这样做:
#include <vector> // required for std::vector
std::vector<QFutureWatcher<bool>*> procWatchers;
虽然根据these documentation examples中 QFutureWatcher
的使用方式,您可能希望将QFutureWatcher
个实例存储在std::vector
中:
std::vector<QFutureWatcher<bool> > procWatchers;
这样您就不必手动 new
和delete
QFutureWatcher
个实例。
显然是QFutureWatcher
inherits from QObject
,uncopyable。这会阻止std::vector<QFutureWatcher<bool> >
工作。
你有这个:
QFutureWatcher<bool> *procwatcher;
procwatcher = new QFutureWatcher<bool>();
QFuture<bool> procfuture = QtConcurrent::run(this, &EraserBatch::processTile);
procwatcher->setFuture(procfuture);
QFutureWatcher<bool> *procwatcher2;
procwatcher2 = new QFutureWatcher<bool>();
QFuture<bool> procfuture2 = QtConcurrent::run(this, &EraserBatch::processTile);
procwatcher2->setFuture(procfuture2);
您可以这样做:
// Not tested!
// Bundle QFutureWatcher and QFuture together.
template<typename T>
struct FutureStruct
{
FutureStruct(QFutureWatcher<T>* w, const QFuture<T>& f)
: watcher(w), future(f)
{
this->watcher->setFuture(this->future);
}
QFutureWatcher<T>* watcher; // Apparently QObjects can't be copied.
QFuture<T> future;
};
// ...
std::vector< FutureStruct<bool> > futures;
// ...
void AddFuture()
{
futures.push_back(FutureStruct<bool>(new QFutureWatcher<bool>(),
QtConcurrent::run(this, &EraserBatch::processTile)));
}
// ...
futures[0].watcher; // gets you the first QFutureWatcher<bool>*
futures[0].future; // gets you the first QFuture<bool>
futures[1].watcher; // gets you the second QFutureWatcher<bool>*
futures[1].future; // gets you the second QFuture<bool>
// ...
当然,因为QFutureWatcher<bool>
已分配new
,所以在delete
向量消失之前,您需要futures
:
for(std::vector< FutureStruct<bool> >::iterator i = futures.begin();
i != futures.end(); ++i)
{
delete i->watcher;
}
答案 1 :(得分:2)
RAII方式,如果观察者不仅由向量拥有:
typedef boost::shared_ptr<QFutureWatcher<bool> > ProcWatcherPtr;
std::vector<ProcWatcherPtr> procWatchers;
如果观察者仅由向量拥有的RAII方式:
typedef QFutureWatcher<bool> ProcWatcher
boost::ptr_vector<ProcWatcher> procWatchers;
或没有内存分配,如果它符合您的需求:
std::vector<QFutureWatcher<bool> > procWatchers;