function pointer

Im not trying to use every c++ feature but i am trying to use them at least a few times so i can remember how to use them if i need to. Im working on fuction pointers right now. ive done a simple example of a function pointer but was wondering if someone could show me a few more useful uses for it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

float squared(float f)
{
	return f*f;
}

int main(int argc, char* argv[])
{
	float(*mysquared)(float f) = squared;

	std::cout << mysquared(12);

	std::getchar();
}
I remember an OpenGL code, where you choose a figure to draw. It was something like:
1
2
3
4
5
6
7
8
9
10
11
12
select(option){
case CUBE: draw = glutSolidCube; break;
case CONE: draw = glutSolidCone; break;
case ICOS:  draw = glutSolidIcosahedron; break;
//...
}

void display(){
  glClear(GL_DEPTH_BUFFER_BIT|GL_COLOR_BUFFER_BIT);
  draw(); //draw what you choose
  glutSwapBuffers();
}


With mathematical procedures, as derivatives, integrals, evaluations, root. The body will be the same, is just the function that it changes. (maybe it will be better to use a functor class)

with filters. You traverse a container and if a condition is met, you perform an action: count_if, remove_if.
And reductions. Sum, average, min, max, product, ...
Another would be for undoing moves in a game; consider that every move is a function, you could store function pointers (alternatively, their arguments) in a STL container to keep track of what happened when.

It's also used a lot for allowing manual control of 'what is executed when' in a few functions I saw implemented (most of them being sorts). Imagine that a function sorts a container conditionally (which is usually what is happening when you sort it). It can sort them from high to low or from low to high. You can do a few things in this scenario:
Add a boolean parameter in which 0 means calling the < operator and 1 means calling the > operator (or vice versa).
Make two separate functions.
Add a function pointer (functor) parameter which is called to determine whether a value should be swapped.

There are a lot more applications of it, but those were the ones I could think of this instant.
Also callbacks.
When an event ocurrs (like a keystroke, mouse movement, timer) you want to execute some function (by instance, move the camera). So you attach the callback to the proper function.
1
2
glutMouseFunction(move_camera);
glutKeyboardFunc(menu);
ok guiys i think i got it. the one about recording moves was interesting. i dont know much about opengl other then its like a state machine. i actually have the redbook and opengl superbible and ive never even opened them.
Last edited on
Topic archived. No new replies allowed.