Table of Contents
std::function is a general-purpose polymorphic function wrapper provided by the C++ Standard Library. It can store, copy, and invoke callable objects such as ordinary functions, lambda expressions, and function objects.
The type of a std::function object is specified using a function signature consisting of the return type and parameter types. This allows different kinds of callable objects with compatible signatures to be used through the same interface.
Source Code #
#include <iostream>
#include <functional>
int add(int first, int second)
{
return first + second;
}
int main()
{
std::function<int(int, int)> operation = add;
int result = operation(10, 20);
std::cout << "Result: " << result << '\n';
return 0;
}
Output #
Result: 30
Explanation #
#include <functional>providesstd::function.std::function<int(int, int)>declares a function wrapper that can store a callable returningintand accepting twointparameters.operation = addstores theadd()function inside thestd::functionobject.operation(10, 20)invokes the stored callable with10and20as arguments.std::functioncan store different callable types as long as their signatures are compatible.- Unlike a function pointer,
std::functioncan also store lambda expressions, function objects, and other callable objects. std::functionprovides a uniform interface for invoking different kinds of callable objects.return 0;terminates the program successfully.