使用范围V3视图来实现begin()/end()方法



是否可以内部在类内使用视图,以实现begin((/end((方法?

例如,我想让以下类迭代;每次迭代 op在两个迭代的当前元素上调用。

template <typename It1, typename It2, typename Op>
struct binary_op {
    binary_op(It1 const& f, It2 const& s, Op o): first{f}, second{s}, op{o} {}
    It1 first;
    It2 second;
    Op op;
};

感谢Range-V3我可以使用zip_with视图(代码未测试!(

ranges::view::zip_with(op, first, second);

但是我可以使用此视图实现begin((/end((方法?

using namespace ranges;
template <typename It1, typename It2, typename Op>
struct binary_op {
    ...
    auto begin() const {
        return view::zip_with(op, first, second).begin();
    }
    auto end() const {
        return view::zip_with(op, first, second).end();
    }
};

可以安全地比较两个迭代器(开始和结束(?

我要实现的最终结果是有可能嵌套任意数量的binary_op:

std::vector<int> v1, v2, v3;
auto r = binary_op(
    binary_op(v1, v2, [](int a, int b) {return a + b;}),
    v3,
    [](int a, int b) {return a - b;});

for (auto x : r) { ... }

看起来很安全,但是仅存储zip_with_view<...>而不打扰binary_op可能会更容易。

请注意,您的示例不是合法的C ,因为Lambda表达式产生了一个对象,而不是类型。您需要

auto op1 = [](int, int) -> int {/*one thing*/};
auto op2 = [](int, int) -> int {/*other thing*/};
auto r = binary_op<
    binary_op<decltype(v1), decltype(v2), decltype(op1)>
    decltype(v3),
    decltype(op2)>{ { v1, v2, op1 }, v3, op2 };

在这一点上,您也可以

auto r = view::zip_with(op2,
                        view::zip_with(op1, v1, v2),
                        v3);

最新更新