Pointer to function

A C++ programmer could use almost indifferently a pointer to function, a functor, or a lambda function to implement the same design request. But pointer to functions are so contrived, difficult to read and maintain, that are commonly used only when one can't avoid to do it. Namely when developing in pure C.

I guess you know what a pointer to function is, and how it works, but let's have a tiny example to refresh the matter, before comparing them with functor and lambda functions.

Say that we want a free function to behave polimorfically, it should run an adder or a multiplier, accordingly to a specific situation, on a couple of doubles, and then output the result. We have some obscure constrain (legacy code that uses our free function, probably) that forces us to think in terms of pointer to functions.

These are the functions that have to be called:
double sum(double a, double b) { return a + b; }
double multiply(double a, double b) { return a * b; }
We define what is the type of a pointer to these functions:
typedef double (*PDF_DD) (double, double);
As one would expect, we defined PDF_DD as a pointer to a function that gets in input two doubles and gives back another double.

This is a possible implementation for our function:
void dispatcher(double x, double y, PDF_DD f) // 1
{
    if(f == NULL) // 2
    {
        std::cout << "Bad pointer to function!" << std::endl;
        return;
    }
    double result = (*f)(x, y); // 3
//  double result = f(x, y); // 4
    std::cout << "Result is: " << result << std::endl;
}
1. The third input parameter is a pointer to function, as defined above.
2. Being a pointer (to function or data doesn't matter), f could be NULL. So we should check it, to avoid the risk of a NULL dereferencing crash.
3. The pointer to function is dereferenced, and the actual function is called. It is not mandatory explicitly dereferencing a pointer to function, the compiler is smart enough to do it implicitly.
4. Same as (2), but relying on the compiler to convert the pointer to function, before calling the referenced function.

The function should be called like this:
dispatcher(3, 2, sum);
dispatcher(3, 2, multiply);
dispatcher(3, 2, NULL); // 1
1. PDF_DD is a pointer, so this code is legal. Hence we should remember to check this parameter value before dereferencing it.

No comments:

Post a Comment