C++ Logo

std-discussion

Advanced search

Re: lambda, capture by const-ref

From: Andrew Schepler <aschepler_at_[hidden]>
Date: Fri, 17 Sep 2021 19:13:22 -0400
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__)

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.

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? 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".) Can I
have implicitly captured variables be references to const using [const &,
&ref, copy]? 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".

-- Andrew Schepler

Received on 2021-09-17 18:13:35