假设我有一些基于数组的代码可供表达式模板使用。例如,我operator[]对这些数组进行了重载,并且还重载了算术运算符+等。
现在我想让 STL 算法any_of在这样的数组上运行。简单的方法是做
ExprArray<double, N> b, c; // init etc.
auto a = b + c; // for (auto i = 0; i < N; ++i) { a[i] = b[i] + c[i]; }
auto res = std::any_of(begin(a), end(a), SomePred{});
当然,我希望能够缩短计算并进行修改(基于范围lib::any_of)
// only compute b[i] + c[i] until SomePred is satisified
auto res = lib::any_of(b + c, SomePred{}); // write as explicit loop over b[i] + c[i]
lib::any_of在其输入上写入operator[]将完成这项工作,就像为重载 . 所做的一样operator+。但是,这需要对我可能在此类数组上运行的所有 STL 算法进行类似的重新实现。
问题:所以假设我想通过仅修改ExprArray iterators. 是否可以修改ExprArray迭代器operator*并且operator++以对基于范围的算法透明的方式进行?
// only compute b[i] + c[i] until SomePred is satisified
// needs to eventually dispatch to
// for (auto i = 0; i < N; ++i)
// if (SomePred(b[i] + c[i])) return true;
// return false;
auto res = ranges::any_of(b + c, SomePred{});
因此,如果算法版本实际上是根据迭代器实现的,则循环for (auto it = first; it != last; ++it)需要*it知道它需要计算的事实b[i] + c[i],并且++it必须知道它需要做的事实++i。