Welcome to the exciting world of C++11's std::function! In this comprehensive guide, we'll explore how to harness the power of this versatile tool, suitable for both beginners and intermediates.
std::function is a C++11 template that allows you to store and call function objects. It provides a uniform interface for a variety of function types, enabling polymorphic function calls and facilitating functional programming in C++.
std::functionLet's create our first std::function and learn how to store and call a simple function:
#include <functional>
#include <iostream>
int add(int a, int b) {
return a + b;
}
int main() {
std::function<int(int, int)> adder; // Declare an `std::function`
adder = add; // Assign the add function to adder
int sum = adder(3, 5); // Call the function using adder
std::cout << "3 + 5 = " << sum << std::endl;
return 0;
}Understanding function types is crucial to utilizing std::function effectively. C++ defines function types based on the number and type of its parameters and the return type. For example, the function add(int, int) has the type int(int, int).
Calling an std::function is as simple as calling a regular function:
adder(7, 9); // Output: 16You can also call std::function with a different number or type of arguments using std::placeholders.
std::function is a powerful tool in C++11, enabling functional programming techniques like higher-order functions, lambdas, and polymorphic function calls.
Here's an example of a simple higher-order function using std::function:
#include <functional>
#include <iostream>
#include <vector>
void process(std::function<void(int)> func, std::vector<int> numbers) {
for (int number : numbers) {
func(number);
}
}
void print_number(int number) {
std::cout << number << std::endl;
}
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
process(print_number, numbers); // Output: 1, 2, 3, 4, 5
return 0;
}Which of the following is the correct function type for the `add(int, int)` function?
Happy coding, and remember to practice, practice, practice! šÆš”š