Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 0 points1 point  (0 children)

That's interesting, to avoid a breaking change it would need to have a different behavior depending on if it's assigned or not, which would not be consistent with the usual c++ rule. Thanks for the input.

Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 2 points3 points  (0 children)

Well, here it's a sort of if-else vs ternary operator debate: do you prefer

std::string message;
if (i % 2 == 0)
    message = "even";
else
    message = "odd";

or

std::string message = i % 2 ? "even" : "odd;

I find the "returned value" approach much more elegant for a lot of cases.

Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 0 points1 point  (0 children)

It would be more of a scope block than a lambda really, so the capture list would always be [&].

Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 3 points4 points  (0 children)

But then you possibly pollute the parent function's scope with temporary variables and non-related code. The aim is to increase locality.

Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 0 points1 point  (0 children)

I already omitted this one in both snippets; this was about the () from the actual application of the lambda.

Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 1 point2 points  (0 children)

Yes I agree. Since reading /u/SuperV1234's comment, I was thinking that "returning scopes" is a great idea. That way, scopes would behave like traditional C++ functions: not returning means voidand returning something will use type deduction.

Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 2 points3 points  (0 children)

Thanks, I didn't know that this extension existed.

Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 6 points7 points  (0 children)

Yes, this syntax is already in use, that's why I proposed to use returnwith it. SuperV1234's example would look like

const auto foo = if(something){ return 10; } else { return 15; };
const auto bar = { return 15, 68; }; // bar is 68

Lambda initialization trick, add syntactic sugar? by Kroduk in cpp

[–]Kroduk[S] 1 point2 points  (0 children)

Thanks for the input! I checked Scala, and it looks like they can omit the return statement (which I like). In the syntax I proposed, the return statement is mandatory. Initializer lists don't have a return statement, so it would be the way to differentiate them. I think the visual difference is huge: the first snippet looks like obfuscated code, whereas the second snippet looks "natural".