- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 389字
- 2021-06-10 18:28:08
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.
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.