Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,695 questions

57,003 answers

573 users

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
...