Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you define a lambda with a name in the capture-list of a lambda-expression, but not outside of it?

Tags:

c++

syntax

lambda

I've read the explanation of lambda expressions in C++, and I've seen how they work, and how a lambda-expression needs to be declared (many details omitted):

[ lambda-captureopt ] ( parameter-declaration-clause ) compound-statement.

I've seen that you can define a lambda inside another lambda definition in a way like this:

[lambda1{[](){
    return 123;
}}]{
    return lambda1();
}

This works:

cout << [lambda1{[](){
    return 123;
}}]{
    return lambda1();
}();

This one doesn't:

cout << prova{[](){
    return "hello";
}}();

Why can I define it like lambda1{...} in the second example and not in the third?

like image 532
Lorenzo Spada Avatar asked Sep 21 '25 04:09

Lorenzo Spada


1 Answers

In the second example, [lambda1{[](){...}}]{...} you see that the identifier lambda1 occurs within brackets[] that are the capture list of the lambda. This is a context where a new identifier, lambda1, can be declared.

In the third example, the identifier prova occurs without any "special" context, in particular, not one where a new identifier can be declared. Hence, it is looked up in the usual way, and if it is not found, you have an error.

like image 85
j6t Avatar answered Sep 22 '25 18:09

j6t