C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Add Projection Support for std::ranges::views

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Thu, 14 Sep 2023 18:12:03 +0100
On Thu, 14 Sept 2023 at 16:06, Grzegorz Sikorski via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Thanks all for your answers. I obviously misread the description in
> https://en.cppreference.com/w/cpp/ranges/filter_view (in other places the
> overload for a projection is explicitly shown). Yes, this helps a lot and
> solves one problem. However the original issue I was trying to fix recently
> was this: https://godbolt.org/z/TW8P5xqxz. I use range-v3 as a
> polyfill for the missing std::views::chunk_by, maybe this is the problem.
>

Firstly, std::views::chunk_by is not missing, it's part of C++23 so
available if you use -std=c++23


Secondly, your attempts to use it are incorrect, that's why it doesn't
work. The argument needs to be a binary predicate, so neither of these is
correct:

// Neither of below work:
// auto active_buttons = buttons |
ranges::views::chunk_by(&Button::enabled, std::equal_to<bool>{});
// auto active_buttons = buttons |
ranges::views::chunk_by(&Button::enabled);

 This works:

auto active_buttons = buttons | std::views::chunk_by([](auto& l, auto& r){
return l.enabled == r.enabled; });

The problem here is not related to lack of support for projections, it's
that you need a binary predicate and &Button:enabled is not a binary
predicate.




> On Wed, 13 Sept 2023 at 20:10, Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
> wrote:
>
>> On Wed, Sep 13, 2023 at 11:20 AM Grzegorz Sikorski via Std-Proposals <
>> std-proposals_at_[hidden]> wrote:
>>
>>> I started to notice a pattern that appears in many places. Consider a
>>> code like this:
>>>
>>> struct Button {
>>> std::string name;
>>> bool enabled;
>>> };
>>>
>>> auto get_enabled(const auto& buttons) {
>>> return std::ranges::views::filter([](const auto& button) { return
>>> button.enabled; });
>>> }
>>>
>>> What I find useful is to add something like
>>> https://godbolt.org/z/7Y5bdeddd. Projection support could also be
>>> useful in some other std::ranges::views namespace members.
>>>
>>
>> Nit: Write `std::views::filter`, not `std::ranges::views::filter`.
>> Core confusion: Are you asking for C++20 to support std::invoke'ing a
>> member data pointer? Because it already does. Example:
>> https://godbolt.org/z/sqjxG3dW5
>> return std::views::filter(&Button::enabled);
>>
>> –Arthur
>>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2023-09-14 17:12:18