Skip to content

HowTo write a View add constant_smaller

sarahet edited this page Feb 16, 2018 · 3 revisions

A smaller version without custom view_add_constant

This time we will make use of ranges::view::transform and not implement our own view. This means from the three entities described previously, the first is no longer needed. ranges::view::transform takes a lambda function that it applies to all elements:

struct add_constant_fn
{
    template <typename irng_t>
        requires /*input_range_concept<irng_t> &&*/
                std::is_same_v<std::decay_t<ranges::range_reference_t<irng_t>>, uint64_t>
    auto operator()(irng_t && irange) const
    {
        return ranges::view::transform(std::forward<irng_t>(irange), [] (uint64_t const in) { return in + 42; });
    }

    template <typename irng_t>
        requires /*input_range_concept<irng_t> &&*/
                std::is_same_v<std::decay_t<ranges::range_reference_t<irng_t>>, uint64_t>
    friend auto operator|(irng_t && irange, add_constant_fn const &)
    {
        return ranges::view::transform(std::forward<irng_t>(irange), [] (uint64_t const in) { return in + 42; });
    }

};

You can use this in combination with the previously introduced instance:

namespace view
{
    add_constant_fn const add_constant;
}

If you prepend all of the above to the test on HowTo write a View it should work.

An even smaller version

Or you can even get rid of the generator and use the transform directly:

namespace view
{
    auto const add_constant =  ranges::view::transform([] (uint64_t const in) { return in + 42; });
}

This creates a new generator that has the lambda hardcoded, but otherwise acts like transform and in our case does all we want. In this case, the first and second entities are no longer needed.

If you can, write your views as combinations of existing views. But be aware that this is not always possible and sometimes the performance overhead or the loss of flexibility make writing your own complete implementation necessary.

Clone this wiki locally