Returning Function Pointers from Functions

How can I return a function pointer from a function in C++? What are some use cases for doing this?

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:

  1. Configuring behavior - Returning different function pointers based on configuration or environment allows flexibly changing functionality.
  2. Memoization - Capturing data in the closure of the returned function enables caching/memoization of expensive operations.
  3. Dependency injection - Caller can provide functions to be called by the callee, enabling inversion of control.

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

First Class Functions

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

Questions & Answers

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

Capturing Local Variables in C++ Lambdas
How can I capture local variables from the enclosing scope when using lambdas in C++? What are the different capture modes and when should I use each?
Downcasting Function Pointers in C++
Is it possible to downcast a function pointer to a more specific function pointer type in C++? For example, casting a pointer-to-base to a pointer-to-derived. If so, how is it done and what are the risks?
Function Pointers and Virtual Functions
How do function pointers interact with virtual functions in C++? Can I take a pointer to a virtual function?
Understanding Complex Function Pointer Syntax
C++ function pointer syntax can get quite complex, especially with things like typedef and using directives. How can I decipher complex function pointer syntax?
Function Pointers and Static Member Functions
Can I take a function pointer to a static member function in C++? How is it different from taking a pointer to a non-static member function?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant