You can return a function pointer from a function just like you would return any other pointer type. The syntax looks like this:
bool greater(int a, int b) { return a > b; }
bool (*GetComparator())(int, int) {
return greater;
}
This function returns a pointer to a function that takes two int
parameters, and returns a bool
. The returned function checks if the first parameter is greater than the second.
Some use cases for returning function pointers include:
For example, a sorting function could allow specifying the comparison operation:
#include <algorithm>
#include <iostream>
#include <vector>
bool less(int a, int b) { return a < b; }
bool greater(int a, int b) { return a > b; }
bool (*GetComparator(bool asc))(int, int) {
return asc ? less : greater;
}
int main() {
std::vector<int> v{5, 2, 3, 4, 1};
std::sort(
v.begin(), v.end(), GetComparator(true));
for (int i : v) {
std::cout << i << ' ';
}
}
1 2 3 4 5
Answers to questions are automatically generated and may not have been reviewed.
Learn about first-class functions in C++: a feature that lets you store functions in variables, pass them to other functions, and return them, opening up new design possibilities
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course