C++ Logo

std-discussion

Advanced search

Re: lambda, capture by const-ref

From: Federico Kircheis <federico.kircheis_at_[hidden]>
Date: Sat, 18 Sep 2021 09:52:15 +0200
On 18/09/2021 01.13, Andrew Schepler wrote:
> On Wednesday, 15 September 2021 14:05:06 PDT Federico Kircheis via
> Std-Discussion wrote:
> > So, to sum it up, I would like see the possibility to add const to
> the lambda capture.
>
> Hi Federico, you do make some good arguments for this. It does seem like
> a fairly natural extension of the existing syntax and functionality.
>
> One nitpick, which actually makes the macro solution trickier and the
> proposal a little more attractive: If we have "std::string&
> get_value();", then C_REF(get_value()) is an lvalue of type std::string
> - no "const" was added. You would need instead:
>
> #define C_REF(...) static_cast<const
> std::remove_reference_t<decltype((__VA_ARGS__))>&>(__VA_ARGS__)


Gasp, apparently I did not test my macro enough.

> I also doubled the parentheses for decltype - I can't see a case where
> it would actually make a difference here, but it seems safer since
> decltype((expr)) is more consistent than decltype(expr) when the
> expression could be arbitrary.

As expressions inside decltype are not evaluated, I thought that there
would be no reason to add the second pair of parenthesis.
Or are you thinking about something else?

> If you're going to move forward with this, some questions to consider:
> Can I leave off the initializer, so that [const & var] captures a local
> variable or surrounding capture with the same name?

I suppose yes, not doing it would add an inconsistency.

> Can I also do [a =
> get_a(), const b = get_b()]() mutable {} to capture by copy and make the
> member const? (This only makes sense when the lambda is "mutable".)

Again, yes.

> Can
> I have implicitly captured variables be references to const using [const
> &, &ref, copy]?

Yes

> In each case an answer of "yes" could make the proposal
> more general and powerful, but possibly open up more questions and
> strange corner cases to consider and complicate the needed wording. An
> answer of "no" could avoid the complexity, but leave programmers
> wondering "why not".

To me it seemed the contrary, prohibiting in some places const would
make the wording more complex.

Thinking about how the compiler generates a lambda with a structure,
member variables and operator(), I do not have any strange corner case
in mind, do you have any?

I admit I have no idea how the wording would look like, I hoped to get
some help here :D.

I thought something like "If the const qualifier is present, then the
captured value(s), or reference(s) is const".
Or write "as-if there would be the static_cast you wrote".

Received on 2021-09-18 02:56:20