Standard Library Function Helpers

Invoking Multiple std::function Objects

How can I store and invoke multiple std::function objects?

Abstract art representing computer programming

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:

  1. A plain function Function1.
  2. A std::bind expression that binds Function2 with the argument 42.
  3. A lambda expression that prints a message.
  4. A 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 computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved