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 12 hours ago 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 12 hours ago 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 11 hours ago by avibootz

Related questions

5 answers 3 views
4 answers 9 views
3 answers 12 views
2 answers 149 views
149 views asked Oct 20, 2020 by avibootz
2 answers 269 views
269 views asked Oct 7, 2020 by avibootz
...