How to use closure in C++

3 Answers

0 votes
#include <iostream>

/*
[capture](parameters) -> return_type {
    body
};

*/

// [=] - capture everything by value

int main() {
    int x = 10;
    int y = 20;

    // A closure (anonymous function) that captures x and y by value.
    // [=] means "capture all used variables by value".
    auto add = [=]() {
        return x + y;
    };

    // Use the closure
    int result = add();

    std::cout << result << std::endl;
}



/*
run:

30

*/

 



answered Jun 2 by avibootz
0 votes
#include <iostream>

/*
[capture](parameters) -> return_type {
    body
};

*/

// [&] - capture everything by reference

int main() {
    int counter = 0;

    // Capture by reference so the lambda can modify counter
    auto inc = [&]() {
        counter++;
    };

    inc();
    inc();

    std::cout << counter << std::endl; 
}



/*
run:

2

*/

 



answered Jun 2 by avibootz
0 votes
#include <iostream>

/*
[capture](parameters) -> return_type {
    body
};

*/

// Closure with parameters

int main() {
    auto multiply = [](int a, int b) {
        return a * b;
    };

    std::cout << multiply(6, 7) << std::endl;
}



/*
run:

42

*/

 



answered Jun 2 by avibootz

Related questions

4 answers 249 views
4 answers 287 views
4 answers 252 views
5 answers 343 views
4 answers 263 views
...