What is std::function in C++: Explanation and Example
std::function is a flexible wrapper for any callable object like functions, lambdas, or function objects. It allows you to store, pass, and invoke these callables uniformly, making your code more flexible and reusable.How It Works
Think of std::function as a universal remote control for calling different types of functions. Instead of needing a separate remote for each device, you have one that can control many. Similarly, std::function can hold any callable entity that matches a specific function signature, such as a regular function, a lambda expression, or a function object.
When you assign a callable to a std::function, it stores it internally and lets you call it later using the same syntax. This means you can write code that works with any callable without knowing its exact type beforehand, which is very useful for callbacks, event handlers, or passing behavior as arguments.
Example
This example shows how to use std::function to store and call different types of functions with the same signature.
#include <iostream> #include <functional> // A regular function int add(int a, int b) { return a + b; } int main() { // std::function that takes two ints and returns an int std::function<int(int, int)> func; // Assign a regular function func = add; std::cout << "add(2, 3) = " << func(2, 3) << "\n"; // Assign a lambda function func = [](int x, int y) { return x * y; }; std::cout << "lambda multiply(2, 3) = " << func(2, 3) << "\n"; // Assign a function object struct Subtract { int operator()(int a, int b) const { return a - b; } } subtract; func = subtract; std::cout << "subtract(5, 3) = " << func(5, 3) << "\n"; return 0; }
When to Use
Use std::function when you want to store or pass around functions or callable objects without caring about their exact type. It is especially helpful for:
- Callbacks in event-driven programming, where you want to call a function later when an event happens.
- Passing behavior as arguments to other functions, enabling flexible and reusable code.
- Storing different kinds of callables in containers or variables uniformly.
For example, in GUI programming, you might use std::function to store button click handlers that can be regular functions, lambdas, or member functions.
Key Points
std::functioncan hold any callable matching a specific signature.- It provides a uniform way to store and invoke functions, lambdas, and function objects.
- It adds some overhead compared to direct function calls but offers great flexibility.
- Useful for callbacks, event handlers, and passing functions as arguments.
Key Takeaways
std::function is a flexible wrapper for any callable with a matching signature.