Quantcast
Viewing latest article 4
Browse Latest Browse All 6

Answer by Neil for How can I write a beautiful inline recursive lambda in C++?

If you don't have access to C++23 then you can wrap your lambda in another lambda that hides the extra argument, e.g. like this:

int main(int argc, char **argv) {    auto fact = [&](int x) -> int {        auto do_fact = [&](const auto &self, int x) -> int {            return x ? x * self(self, x - 1) : 1;        };        return do_fact(do_fact, x);    };    return fact(argc);}

clang with -O and gcc with -O2 will compile the above into a simple multiplication loop (clang tries to be extra clever at higher optimisation levels).


Viewing latest article 4
Browse Latest Browse All 6

Trending Articles