c++ - C++ 中的模板化类型数组

标签 c++ arrays templates

我有以下内容:

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;

这样你就不必手动 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 之前 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/

相关文章:

C++(控制台)构造函数和派生类

C++成员函数模板使用template

arrays - 加权中位数 - 数组的 UDF?

c++ - 'point' 的初始化没有匹配的构造函数

c++ - Q. 速度在 "R with indicator"和 "c++ with for"之间

c++ - 引用表溢出(最大值=1024)

python - 使用 numpy 将数组元素添加到矩阵的每一列

javascript - 根据多维数组中的两个值查找唯一项

c++ - 如何处理模板类的 vector ?

templates - 如何为 MacVim 创建骨架文件或模板