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.
Answers to questions are automatically generated and may not have been reviewed.
Learn about function pointers: what they are, how to declare them, and their use in making our code more flexible