我有以下内容:
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;
虽然根据如何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
, 你需要 delete
它在 futures
之前 vector 消失了:
for(std::vector< FutureStruct<bool> >::iterator i = futures.begin();
i != futures.end(); ++i)
{
delete i->watcher;
}
关于c++ - C++ 中的模板化类型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7095139/