【发布时间】:2019-06-11 11:11:24
【问题描述】:
在我的代码中,我经常有函数在不同的可迭代 Qt 容器类型上执行相同的操作,例如:
void removeX(QMap<qint64, QString> & map)
{
QMutableMapIterator<qint64, QString> it(map);
while (it.hasNext()) {
it.next();
if (it.value() == "X") it.remove();
}
}
void removeX(QList<QString> & list)
{
QMutableListIterator<QString> it(list);
while (it.hasNext()) {
it.next();
if (it.value() == "X") it.remove();
}
}
(我知道 QList 中已经有一个 removeAll 函数。这只是一个愚蠢的最小示例)
实际代码更复杂,因此会引入大量代码重复。我希望有类似的东西:
template <typename T>
void removeX_(T & container)
{
typename T::mutable_iterator it(container);
while (it.hasNext()) {
it.next();
if (it.value() == "X") it.remove();
}
}
当然,这不会编译,因为 Qt 中根本没有 "::mutable_iterator" 类型定义。一个人可以建造一个吗?我没有看到一个简单的方法。在这种情况下,像“template<...> getMyMutableIterator”这样的函数不能工作,因为我们不允许为重载函数返回不同的类型。
但是我还没有真正理解 C++17 中的许多新的“模板魔法”。我可以想象这可能是实现上述代码的一种简单方法。有没有人在这里减少代码重复的解决方案?
【问题讨论】:
-
你试过
std::remove_if(container.begin(), container.end(), [](auto& x) { return x.value() == "X"});QMap和QList都提供了一个STL迭代器接口。 -
我知道有
remove_if,但实际代码更复杂。例如,如果满足某些我想在同一个函数中检查的条件,则容器保持不变或完全清除。
标签: c++ qt templates iterator c++17