How to create a lambda function stored inside std::function (store and use a callback function) in C++

1 Answer

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

int main() {

    // A lambda expression that takes two integers (a, b)
    // and returns the remainder of a divided by b.
    // The type is deduced automatically using 'auto'.
    auto mod1 = [](int a, int b) { return a % b; };

    // Call the lambda and print the result
    std::cout << "mod1(12, 5) = " << mod1(12, 5) << "\n";


    // std::function explicitly stores a callable object
    // with the signature: int(int, int)
    // Here we assign another lambda that performs modulus.
    std::function<int(int, int)> mod2 = [](int a, int b) { return a % b; };

    // Call the std::function-wrapped lambda and print the result
    std::cout << "mod2(17, 3) = " << mod2(19, 4) << "\n";
}



/*
run:

mod1(12, 5) = 2
mod2(17, 3) = 3

*/

 



answered May 15, 2021 by avibootz
edited Mar 20 by avibootz
...