Storing Function Pointers

How can I store multiple function pointers of the same type in a collection like a vector or array?

To store multiple function pointers of the same type in a collection, you can use the same type alias approach we showed in the lesson. For example:

#include <iostream>
#include <vector>

using IntPredicate = bool (*)(int);

bool isEven(int n) { return n % 2 == 0; }

bool isPositive(int n) { return n > 0; }

int main() {
  std::vector<IntPredicate> Predicates{
    isEven, isPositive};

  for (auto& Pred : Predicates) {
    std::cout << std::boolalpha;
    std::cout << Pred(4) << '\n';   
    std::cout << Pred(-1) << '\n';  
  }
}
true
false
false
false

Here, we define an IntPredicate type alias for a function pointer that takes an int and returns a bool. We can then use this alias to specify the type stored in our vector.

We populate the vector with our isEven and isPositive function pointers. Later, we can iterate over the vector and call each function pointer with the () operator, just like we would with a normal function.

This same approach works for arrays and other collections that can store the function pointer type.

Function Pointers

Learn about function pointers: what they are, how to declare them, and their use in making our code more flexible

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Pointers to Member Functions
Is it possible to create a pointer to a member function of a class? If so, how is it different from a regular function pointer?
Capturing this in Lambdas
How can I use a lambda to create a function pointer that calls a member function of my class?
Function Pointers and Const
How does const-correctness apply to function pointers? Can I have a pointer to a const function?
Function Pointers and Inheritance
Can I assign a derived class member function to a base class function pointer? How does inheritance affect function pointers?
Using Function Pointers with STL Algorithms
Can I use function pointers with STL algorithms like std::find_if or std::sort? How can I pass a function pointer as a predicate or comparison function?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant