std::function
in C++
std::function
is a class template in C++ (introduced in C++11) that provides a type-erased way to store and invoke any callable entity (functions, lambda expressions, function objects, member function pointers, etc.). It's a powerful tool for working with callbacks, event handlers, and other situations where you need to pass around or store a function or function-like object without knowing its specific type at compile time.
std::function
acts as a generic wrapper for any callable with a compatible signature. You specify the function signature (return type and parameter types) when you declare a std::function
object.
#include <iostream>
#include <functional>
int add(int a, int b) {
return a + b;
}
int main() {
// Store a regular function
std::function<int(int, int)> func1 = add;
int result1 = func1(5, 3); // Invoke the function
std::cout << "Result 1: " << result1 << std::endl; // Output: 8
// Store a lambda expression
std::function<void(const std::string&)> func2 = [](const std::string& message) {
std::cout << "Message: " << message << std::endl;
};
func2("Hello from lambda!"); // Output: Hello from lambda!
// Store a function object (functor)
struct Multiply {
int operator()(int a, int b) const {
return a * b;
}
};
Multiply multiplier;
std::function<int(int, int)> func3 = multiplier;
int result3 = func3(4, 6); // Output: 24
std::cout << "Result 3: " << result3 << std::endl;
// Store a member function pointer
struct MyClass {
int myMethod(int x) { return x * 2; }
};
MyClass obj;
std::function func4 = &MyClass::myMethod;
int result4 = func4(&obj, 7); // Output: 14
std::cout << "Result 4: " << result4 << std::endl;
return 0;
}
std::function
).
std::function
comes with a small runtime overhead because of the type erasure. If performance is absolutely critical and you know the type of the callable at compile time, using templates or regular function pointers might be more efficient. However, in most cases, the flexibility and expressiveness of std::function
outweigh the minor performance cost.