Middle
What is std::function in C++?
sobes.tech AI
Answer from AI
std::function is a polymorphic wrapper for any callable objects (functions, function pointers, lambda expressions, functors, member function pointers). It allows unifying the call syntax for various types of objects that can be called.
Main features:
- Storage of callable objects: Can store any object for which the
()operator is defined or that can be invoked as a function. - Type safety: Checks the signature of the stored object at compile time.
- Polymorphism: Allows working with different types of callable objects uniformly.
Example usage:
#include <functional>
#include <iostream>
void simple_function(int x) {
std::cout << "Simple function called with: " << x << std::endl;
}
struct Functor {
void operator()(int x) const {
std::cout << "Functor called with: " << x << std::endl;
}
};
int main() {
std::function<void(int)> func; // Declaration of std::function accepting int and returning void
func = simple_function; // Assigning a function
func(10);
func = [](int x) { // Assigning a lambda expression
std::cout << "Lambda called with: " << x << std::endl;
};
func(20);
func = Functor(); // Assigning a functor
func(30);
return 0;
}
std::function is convenient for implementing callbacks, storing functions from various sources with a unified interface, and passing callable objects as function arguments. Keep in mind that using std::function may incur slight overhead compared to direct calls or template usage, related to memory allocation and virtual calls.