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.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.
auto func = [](...){....}
for nested funcs
typedef void fp_t();
void foo(fp_t fp)
{
fp();
}
int square(int num) {
void square_nested()
{
num = num * num;
}
foo(square_nested);
return num;
}
That would work as long as you don't need copy capture. int square(int num) {
auto nested = [&num](){
num *= num;
};
nested(num);
return num;
} auto nested = [](int& num){
(or switch calling nested to have no params)https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html#Nes...
std::sort(vec.begin(), vec.end(),
[] (const auto& lhs, const auto& rhs) {
return lhs.whatever < rhs.whatever;
});
or auto sort_by_whatever = [] (const auto& lhs, const auto& rhs) {
return lhs.whatever < rhs.whatever;
};
std::sort(vec.begin(), vec.end(), sort_by_whatever); const auto iAmANestedFun = [stuff](stuff) -> stuff { ... }
Particularly, if we could assume that nested functions automatically and properly capture the arguments to the parent function. const auto nestedfunc = [=](a,b) { /* */ };
Which isn't that much different to me than { /* some scope */
function nestedfunc(a,b) { /* */ }
}
const and auto are needed but because it's C++. Beyond that, you have an equals sign which is needed here but [=] which is three characters. Again, small differences, not sure why it looks that much worse. auto triple = [](auto x){ return 3 * x; };well, how would you do that ?
IIRC Rust uses capture modifiers similar to C++.
PHP closures have to specify which variables they close over, and whether it's done by-val or by-ref [0].
Nowadays there's also a shorthand single-expression-closure syntax that closes implicitly and by value [1].
[0]: https://www.php.net/manual/en/functions.anonymous.php#exampl...
auto f = [&](...) { ... };
That covers the majority of cases.