c++rangec++20

Why does the ranges library define two names for each view?


In the ranges library for c++20, all the views have a second version.

For instance, std::ranges::views::filter

According to cppreference:

The expression views::filter(E, P) is expression-equivalent to filter_view{E, P} for any suitable subexpressions E and P.

We have the actual class, std::ranges::filter_view, and then put inside the views namespace we have std::ranges::views::filter. Is there any difference between the two, or is it purely a matter of style?


Solution

  • all the views have a second version

    No, they do not.

    filter_view is a type. filter is a functor. By calling the filter functor, you can create an object of the corresponding filter_view type (or near-enough).

    But you can also call the filter functor with only one parameter: the filtering predicate. The return value from such a call is an object which you can | against a range to also create a filter_view equivalent, as described on the very page you linked to:

    ints | std::views::filter(even)
    

    You can't do that with filter_view directly.

    So, you can either create a filtering view using common C++ notation: filter_view(range, predicate), or you can do it with a more functional style predicate notation: range | views::filter(predicate).