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
falseHere, 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