![]() |
VOOZH | about |
std::function in C++ is a template class used to store and invoke callable objects such as functions, lambda expressions, and functors. It provides a flexible and generic way to handle callable objects in C++ programs.
Note: std::function is defined in the <functional> header file.
30
Explanation: Above program uses std::function to store the add() function inside a callable wrapper object f. The wrapped function is then invoked using f(10, 20) to calculate and print the sum of two numbers.
To create a wrapper object, we first declare it using the following syntax:
std::function< rtype (atype...)> name();
where,
The above syntax only creates an empty instance of std::function. To wrap a particular function inside this wrapper object, we use assignment operator as shown:
std::function< ret_t (args_t)> name = f;
where f is the function to be wrapped. We can also initialize it at the time of declaration:
std::function< ret_t (args_t)> name(f);
Example: Program to illustrate the working of std::function
Sum: 10 Product: 16
std::function contains some member functions to provide some basic functionality. The following table lists some useful member functions of std::function class template:
Function | Description |
|---|---|
swap() | Swaps the wrapped callable of two std::function objects. |
operator bool | Checks if the |
operator () | Invoke the callable with the given arguments. |
target() | Returns a pointer to the stored callable. If there is no callable stored, returns nullptr. |
target_type() | Returns the |
Apart from the applications shown in the above examples, std::function can also be used for:
The following examples demonstrates the usage of std::function in C++ for different applications such as callbacks, state preserved callbacks, function composition.
Example 1: Passing std::function as Argument (Callback)
Result: 10 Result: 6 Result: 16 Result: 4
Example 2: Wrapping Member Functions of a Class
We can also wrap a member function of a class using std::function object but we have to add one extra argument as shown in the below program.
Product: 20
Example 3: Composing Two Functions into One
18
Explanation: In this example, we composted two lambda functions add() and mul() into one function cf() which takes two function wrappers and returns another function wrapper. Then we created a wrapper for this using this composed function and use it to perform the addition and multiplication operator at one call.