只要模板是完全专用的(即指定所有模板参数),那么您可以简单地这样做:
#include <vector> // required for std::vector
std::vector<QFutureWatcher<bool>*> procWatchers;
尽管根据QFutureWatcher 在these documentation examples 中的使用方式,您可能希望将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,你需要在futures 向量消失之前delete 它:
for(std::vector< FutureStruct<bool> >::iterator i = futures.begin();
i != futures.end(); ++i)
{
delete i->watcher;
}