Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I sympathize with you here. I kind of like the lambda syntax for simple cases in C++, but the complex cases look painful to me, and based on everything else in C++, I predict there are many special cases to remember.

However, if you just want a more conventional syntax for nested functions, you can almost get what you want by placing a static method inside of a local class, and it's available in older versions of C++ too:

    #include <stdio.h>

    int main() {

        struct foo {
            static void bar() {
                printf("nested\n");
            }
        };

        foo::bar();

        return 0;
    }
If you want it to "close" over your local variables, you'll probably need to actually instantiate an instance of the local class and use a non-static method. Doing this, the capture lists in lambdas almost start to make sense.


Clever. If you let the nesting function have static variables they can be referenced from the nested function too, but actually using lambdas would of course be more clear in practice.

The only feature of lambdas that a proper nested function would miss is the "copy capture".


> The only feature of lambdas that a proper nested function would miss is the "copy capture".

Yeah, reference by default would fit with what people probably expect from other languages, but without a garbage collector (or similar) that's only valid for downward passed functions. Copying allows your nested function to escape the lifetime of the calling function, which might require some other/additional syntax.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: