There are various contexts where you can use function pointers. For example try the following program
#include <iostream>
namespace N
{
void ( * for_each( int *first, int *last, void f( int & x ) ) )( int & )
{
for ( ; first != last; ++first ) f( *first );
return f;
}
}
void f1( int &x ) { std::cout << x << ' '; }
void f2( int &x ) { if ( x % 2 ) x = -x; }
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
N::for_each( a, a + sizeof( a ) / sizeof( *a ), f1 );
std::cout << std::endl;
N::for_each( a, a + sizeof( a ) / sizeof( *a ), f2 );
N::for_each( a, a + sizeof( a ) / sizeof( *a ), f1 );
std::cout << std::endl;
return 0;
}
The output will be
0 1 2 3 4 5 6 7 8 9
0 -1 2 -3 4 -5 6 -7 8 -9
You could introduce a typedef name for the function pointer. In this case the code would look simpler. For example
namespace N
{
typedef void ( *fp )( int & );
fp for_each( int *first, int *last, fp f )
{
for ( ; first != last; ++first ) f( *first );
return f;
}
}
You can use for example arrays of function pointers.
You can use also
std::function instead of or with function pointers and so on.