我有以下内容:

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]等。

谢谢!

最佳答案

只要模板是完全专业化的(即指定了所有模板参数),就可以简单地执行以下操作:

#include <vector> // required for std::vector

std::vector<QFutureWatcher<bool>*> procWatchers;


尽管根据these documentation examplesQFutureWatcher的用法,您可能希望将QFutureWatcher实例存储在std::vector中:

std::vector<QFutureWatcher<bool> > procWatchers;


这样,您将不必手动newdelete 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;
}

10-07 22:19