Invoking Multiple std::function Objects
How can I store and invoke multiple std::function objects?
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: HelloIn 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:
- A plain function
Function1. - A
std::bindexpression that bindsFunction2with the argument42. - A lambda expression that prints a message.
- A
std::bindexpression that binds theoperator()of aFunctorobject 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.
Standard Library Function Helpers
A comprehensive overview of function helpers in the standard library, including std::invocable, std::predicate and std::function.