#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?
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) {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With