c++中模板类型的数组

Array of templated type in C++

本文关键字:数组 类型 c++      更新时间:2023-10-16

我有以下内容:

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在这些文档示例中的使用方式,您可能希望将QFutureWatcher实例存储在std::vector中:

std::vector<QFutureWatcher<bool> > procWatchers;
这样你就不需要手动newdelete QFutureWatcher实例。

显然QFutureWatcher继承自QObject,这是不可复制的。这将阻止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;
}

如果观察者不仅属于vector:

typedef boost::shared_ptr<QFutureWatcher<bool> > ProcWatcherPtr;
std::vector<ProcWatcherPtr> procWatchers;

如果观察者只属于vector:

typedef QFutureWatcher<bool> ProcWatcher
boost::ptr_vector<ProcWatcher> procWatchers;

或不分配内存,如果它适合您的需要:

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