The std::function() in C++ is a function wrapper class which can store and call any function or a callable object. In this article, we will learn about std::function in C++ and how to use it in different cases.
What is std::function in C++?
std::function is a template class in C++ that is used to wrap a particular function or any other callable object such as a lambda, or function object. It is generally used to write generic code where we need to pass functions as arguments in another function (callbacks). It avoids the creation of extra overloads of the function that may take similar callback functions as arguments.
std::function is defined in the <functional> header file.
Declaration
To create a wrapper object, we first declare it using the following syntax:
std::function< rtype (atype...)> name();
where,
- name: Name of the wrapper.
- atype: Types of the arguments that function takes.
- rtype: Return type of the function you want to store.
Initialization
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 of std::function
C++
// C++ Program to illustrate the working
// std::function
#include <bits/stdc++.h>
using namespace std;
int f(int a, int b) {
return a + b;
}
int main() {
// std::function wrapping traditional
// function
function<int(int, int)> calc = f;
cout << "Sum: " << calc(8, 2) << endl;
// std::function wrapping a lambda
// expression
calc = [](int a, int b) { return a * b; };
cout << "Product: " << calc(8, 2);
return 0;
}
OutputSum: 10
Product: 16
Member Functions of std::function
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 std::function contains a callable. |
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 typeid of the callable. If no callable is stored, it returns typeid(void) . |
Applications of std::functions in C++
Apart from the applications shown in the above examples, std::function can also be used for:
- Callbacks: Used for event-driven systems where functions are passed and called later when an event occurs.
- Function Wrapping and Higher-Order Functions: Allows passing functions as parameters and returning them.
- Stateful Callbacks: Enables callbacks with preserved states, making it easier to manage state without global variables.
- Replacing Function Pointers: Provides a safer and more flexible alternative to traditional function pointers, supporting multiple callable types.
More Examples of std::function
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)
C++
// C++ program to pass the std::function
// as arguments
#include <bits/stdc++.h>
using namespace std;
// Functions for simple math operations
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int divs(int a, int b) {
return a / b;
}
// Using std::function as parameter
void func(int a, int b,
function<int(int, int)> calc) {
int res = calc(a, b);
cout << "Result: " << res << endl;
}
int main() {
// Calling all the arithmetic functions
func(8, 2, add);
func(8, 2, sub);
func(8, 2, mul);
func(8, 2, divs);
return 0;
}
OutputResult: 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.
C++
// C++ program to demonstrate usage of
// unction with member functions
#include <bits/stdc++.h>
using namespace std;
class C {
public:
int f(int a, int b) {
return a * b;
}
};
int main() {
C c;
// Wrapping member function of C
function<int(C&, int, int)> calc = &C::f;
// Call the member function using function
if (calc)
cout << "Product: " << calc(c, 4, 5);
else
cout << "No Callable Assigned";
return 0;
}
Example 3: Composing Two Functions into One
C++
// C++ program to demonstrate usage of
// std::function for function composition
#include <bits/stdc++.h>
using namespace std;
// Composed function
function<int(int)> cf(function<int(int)> f1,
function<int(int)> f2) {
// Returning a lambda expression that
// in turn returns a function
return [f1, f2](int x) {
// Apply f1 first, then f2
return f2(f1(x));
};
}
int main() {
auto add = [](int x) { return x + 2; };
auto mul = [](int x) { return x * 3; };
function<int(int)> calc = cf(add, mul);
cout << calc(4);
return 0;
}
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.
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Vector in C++ STL C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Templates in C++ C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
C++ Interview Questions and Answers (2025) C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read
Operator Overloading in C++ in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
C++ Standard Template Library (STL) The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorith
9 min read
C++ Classes and Objects In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.C++ ClassesA class is a user-defined data type, which holds its own data members and
9 min read