Functions Pointers by example (en)
Today, a small memento on the different ways to practice Function Pointers in C++.
A function pointer is simply the memory address where a function is located. If our program calls code at this address, it will execute the related function.
And as examples are better than a long explanation, let’s see some examples :
Pointers to simple functions :
We start by creating two functions for basic mathematical operations (addition, multiplication).
These two operations have the same profile (parameters, return value).
The goal now is to delegate the processing of this transaction to allow a call like this :
So, let’s create this function :
Some explanations :
- The two first parameters are integers (value1 and value2).
- Third parameter is a function pointer :
- it takes two integers as parameters.
- it returns an integer.
- The calculated function call the third parameter function with the 2 first parameters.
We can now call the calculation function :
Tip: With a typedef, you can make the writing of this code a bit more readable:
Pointers to functions (but not only):
With templates :
The objective here is to do the work at compile rather than during the execution.
The calculation function is going to take a template corresponding to an operation:
The advantage is that you can now pass objects such as the following :
With std :: function (from c ++ 0x) :
Another way is to use the function type of the stl (#include). The calculation function becomes:
The corresponding call is exactly the same as before :
But the novelty is that the lamda can also be used (or anonymous functions). For example:
And, it’s over.
This article may contain mistakes, do not hesitate to let me know.