Understanding std::function in C++
std::function is a template class introduced in C++11 that serves as a general-purpose wrapper for callable entities. It allows you to store, copy, and invoke a variety of callable objects using a uniform interface.
Callable objects in C++ include:
- Free functions
- Lambda expressions
- Function objects (functors)
- Member functions
- Other callable types
Here are examples of different callable types:
// Free function
int multiply(int x) {
return x * 2;
}
// Lambda expression
auto square = [](int n) { return n * n; };
// Functor
struct Adder {
int increment;
Adder(int inc) : increment(inc) {}
int operator()(int value) {
return value + increment;
}
};
std::function provides a consistent way to handle these diverse callable types:
#include <functional>
#include <iostream>
int main() {
std::function<int(int)> executor;
// Assign free function
executor = multiply;
std::cout << "Free function: " << executor(5) << std::endl;
// Assign lambda
executor = square;
std::cout << "Lambda: " << executor(5) << std::endl;
// Assign functor
Adder addFive(5);
executor = addFive;
std::cout << "Functor: " << executor(10) << std::endl;
return 0;
}
The key advantage of std::function is that it abstracts away the specific type of callable object, allowing you to write more flexible and reusable code. You can store different callable types in the same std::function variable and invoke them using identical syntax.
std::function is particularly useful in scenarios where you need to pass callbacks, implement strategy patterns, or create event handling systems where the specific implementation may vary at runtime.