Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `ranges::view::for_each` require the functor must return a model of the `InputRange` concept?

#include <vector>
#include <algorithm>
#include <range/v3/all.hpp>

using namespace ranges;

int main()
{
    auto coll = std::vector{ 1, 2, 3 };
    std::for_each(coll.begin(), coll.end(), [](auto){}); // ok
    coll | view::for_each([](auto){}); // static_assert failure
}

The static_assert error message:

To use view::for_each, the function F must return a model of the InputRange concept.

std::for_each takes a functor which returns void, why does ranges::view::for_each require the functor must return a model of the InputRange concept?

like image 224
xmllmx Avatar asked Nov 17 '18 00:11

xmllmx


1 Answers

You misunderstand what view::for_each() is, it's totally different from std::for_each.

The functor in view::for_each() should return another range, then the final effect is that all the ranges are flattened to a big range.

For example:

auto res = coll | view::for_each([](auto n){ return yield_from(view::ints(0, n)); });

The returned range for every element is {0}, {0, 1}, {0, 1, 2} respectively. The res will be the flattened one: {0, 0, 1, 0, 1, 2}

The counterpart of std::for_each is ranges::for_each:

ranges::for_each(coll, [] (auto) {})
like image 125
llllllllll Avatar answered Oct 14 '22 05:10

llllllllll