To store and invoke multiple std::function
objects, you can use a container such as std::vector
or std::list
. Here's an example of how you can store and invoke multiple std::function
objects using a std::vector
:
#include <functional>
#include <iostream>
#include <vector>
void Function1() {
std::cout << "Function1 called\n";
}
void Function2(int x) {
std::cout << "Function2 called with: "
<< x << "\n";
}
struct Functor {
void operator()(const std::string& str) {
std::cout << "Functor called with: "
<< str << "\n";
}
};
int main() {
std::vector<std::function<void()>> Callables;
Callables.emplace_back(Function1);
Callables.emplace_back(std::bind(Function2, 42));
Callables.emplace_back([] {
std::cout << "Lambda called\n"; });
Functor functor;
Callables.emplace_back(
std::bind(functor, "Hello"));
for (const auto& Callable : Callables) {
Callable();
}
}
Function1 called
Function2 called with: 42
Lambda called
Functor called with: Hello
In this example, we create a std::vector
named Callables
that stores std::function<void()>
objects, i.e., callables that take no arguments and return void
.
We then use emplace_back
to add various callables to the vector:
Function1
.std::bind
 expression that binds Function2
 with the argument 42
.std::bind
 expression that binds the operator()
 of a Functor
 object with the argument "Hello"
.Finally, we use a range-based for loop to iterate over the Callables
vector and invoke each std::function
object using the Callable()
 syntax.
Note that we used std::bind
to adapt callables with different signatures (Function2
and Functor
) to the signature expected by the std::function<void()>
. std::bind
creates a new callable that binds the arguments to the original callable, allowing it to be invoked with the expected signature.
This technique allows you to store and invoke a heterogeneous collection of callables, providing a flexible way to manage and execute multiple std::function
 objects.
Answers to questions are automatically generated and may not have been reviewed.
A comprehensive overview of function helpers in the standard library, including std::invocable
, std::predicate
and std::function
.