How to use lambda function by passing a function object as an argument to another function in C++

2 Answers

0 votes
#include <iostream>
#include <functional>

void call(int num, std::function<void(int)> f) {
    f(num);
}

int main() {
    auto getSquare = [](int a) { std::cout << a * a; };
    
    call(4, getSquare); 
}




/*
run:

16

*/

 



answered Nov 29, 2022 by avibootz
0 votes
#include <iostream>
#include <functional>

void call(std::function<void()> f) { f(); }

int main() {
    int a = 4;
    auto getSquare = [a]() { std::cout << a * a; };
    
    call(getSquare); 
}




/*
run:

16

*/

 



answered Nov 29, 2022 by avibootz
...