(the post is automatically translated by AI)
Introduction
std::function is a C++11 feature defined in the <functional> header. It’s similar to a function pointer in C, but more general: any CopyConstructible Callable object can be stored, copied, and invoked through it.
Examples of such objects include functions, lambda expressions, bind expressions, as well as pointers to member functions and member data.
The stored callable object is referred to as the std::function’s target. If no target is assigned, the std::function is called empty, and invoking it will throw std::bad_function_call.
A callback function is a function passed as an argument to another function, to be called at some later point.
How to Use It
First, let’s look at the std::function class template:
template<class R, class... args>
class function<R(args)>
To use function, you specify the argument type(s) args and the return type R at initialization. These correspond to the parameters and return type of the Callable. Use void for no return value or no arguments.
Example:
std::function<void(int, float)> callback;
This defines a std::function named callback that takes an int and a float and returns nothing.
To assign a target, std::function overloads operator=. If you have a function func that matches the signature, assign it directly:
void func(int a, float b);
callback = func;
Example Program
#include <iostream>
#include <functional>
std::function<void(int, float)> callback;
void add(int a, float b)
{
std::cout << a + b << std::endl;
}
void sub(int a, float b)
{
std::cout << a - b << std::endl;
}
void func(int a, float b, std::function<void(int, float)> c)
{
c(a, b);
}
int main()
{
int a = 5;
float b = 0.3;
// 5 + 0.3
callback = add;
func(a, b, callback);
// 5 - 0.3
callback = sub;
func(a, b, callback);
}