Using function pointers

A function pointer is merely a pointer. This means that you can use it as a variable; you can return it from a function, or pass it as a parameter. For example, you may have some code that performs some lengthy routine and you want to provide some feedback during the routine. To make this flexible, you could define your function to take a callback pointer and periodically in the routine call the function to indicate progress:

    using callback = void(*)(const string&); 

void big_routine(int loop_count, const callback progress)
{
for (int i = 0; i < loop_count; ++i)
{
if (i % 100 == 0)
{
string msg("loop ");
msg += to_string(i);
progress(msg);
}
// routine
}
}

Here big_routine has a function pointer parameter called progress. The function has a loop that will be called many times and every one hundredth loop it calls the callback function, passing a string that gives information about the progress.

Note that the string class defines a += operator that can be used to append a string to the end of the string in the variable and the <string> header file defines a function called to_string that is overloaded for each of the built-in types to return a string formatted with the value of the function parameter.

This function declares the function pointer as const merely so that the compiler knows that the function pointer should not be changed to a pointer to another function in this function. The code can be called like this:

    void monitor(const string& msg) 
{
cout << msg << endl;
}

int main()
{
big_routine(1000, monitor);
return 0;
}

The monitor function has the same prototype as described by the callback function pointer (if, for example, the function parameter was string& and not const string&, then the code will not compile). The big_routine function is then called, passing a pointer to the monitor function as the second parameter.

If you pass callback functions to library code, you must pay attention to the calling convention of the function pointer. For example, if you pass a function pointer to a Windows function, such as EnumWindows, it must point to a function declared with the __stdcall calling convention.

The C++ standards uses another technique to call functions defined at runtime, which is, functors. It will be covered shortly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset