gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
show me some examples in c++ with std function
- User
show me some examples in c++ with std function
- Assistant
Here are some examples of using the std::function in C++:
- Defining a function object using std::function:
#include <iostream> #include <functional> int main() { // Define a function object using std::function std::function<int(int, int)> add = [](int a, int b) { return a + b; }; std::cout << "Addition of 2 and 3 is " << add(2, 3) << std::endl; return 0; }Output:
Addition of 2 and 3 is 5- Using std::function as a callback function:
#include <iostream> #include <functional> // Function that takes a callback function as argument void perform_operation(int a, int b, std::function<int(int, int)> op) { std::cout << "Result: " << op(a, b) << std::endl; } int main() { // Define function objects std::function<int(int, int)> add = [](int a, int b) { return a + b; }; std::function<int(int, int)> multiply = [](int a, int b) { return a * b; }; // Pass the function objects as callback functions perform_operation(2, 3, add); perform_operation(2, 3, multiply); return 0; }