Ch6.14: Higher‑Order Functions
Overview
A higher‑order function is simply a function that takes another function as an argument, or returns a function. You have already seen the building blocks: function pointers and captureless lambdas.
In this chapter, you will learn:
- how to pass functions to other functions
- how to return functions from functions
- how to build simple dispatch systems
- how to use captureless lambdas as callbacks
1. Passing functions to other functions
A function pointer parameter allows you to pass behavior into a function.
int operate(int a, int b, int (*op)(int, int))
{
return op(a, b);
}
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
println(operate(3, 4, add)); // 7
println(operate(3, 4, mul)); // 12
This is the simplest form of a higher‑order function.
2. Using captureless lambdas as callbacks
A lambda with no captures can be used anywhere a function pointer is expected.
println(operate(3, 4, [](int a, int b) { return a - b; }));
This is useful for quick one‑off operations.
3. Returning functions from functions
A function can return a function pointer. This allows you to select behavior at runtime.
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int (*select_op(char c))(int, int)
{
if(c == '+') return add;
return sub;
}
auto op = select_op('+');
println(op(10, 3)); // 13
4. Simple dispatch table
You can store multiple functions in an array and choose one at runtime.
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int sub(int a, int b) { return a - b; }
int (*ops[3])(int, int){add, mul, sub};
println(ops[0](3, 4)); // add
println(ops[1](3, 4)); // mul
println(ops[2](3, 4)); // sub
This is the basis of interpreters, state machines, and command dispatchers.
5. Callbacks with parameters
A callback is simply a function passed to another function to be executed later.
void repeat(int n, void (*f)())
{
for(int i{}; i != n; ++i)
f();
}
repeat(3, [] { println("tick"); });
This prints tick three times.
Key takeaways
- A higher‑order function takes or returns a function.
- Function pointers allow you to pass behavior into functions.
- Captureless lambdas can be used as function pointers.
- Returning function pointers enables runtime behavior selection.
- Dispatch tables allow simple interpreters and state machines.