



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




We have got a BST class that can hold integers and that allows users to specify whatever processing they want. But, how about floating point numbers, names, or personal records?
CS 310 A Few C++ Features, 2 ' $
// No machine instructions generated here. The compiler // merely memorizes the template of swap functions. template
main () { int a, b; float c, d; swap (a, b); // copy and paste; function // void swap (int, int) // created ‘‘on spot’’ before invoked swap (c, d); // copy and paste; function // void swap (float, float) // created ‘‘on spot’’ before invoked }
CS 310 A Few C++ Features, 4 ' $
main() { double a; double (p) (double); // declare a pointer to functions // that accept a double parameter // and return a double value p = sin; // have p points to function sin() p(a); // compute sin(a) // you can also use noatation (p)(a); p = cos; // have p points to function cos() p(a); // compute cos(a) }
A function parameter is a pointer parameter that points to functions.
Motive: In the tree traversal functions, the “processing” (that is, printing) applied to each node is fixed. How can we, the designer of the BST, anticipate all the applications/processings to be used with tree traversals?
Solution: We cannot. Instead, let the user of the traversal functions to determine the processing of each node and pass us a pointer to the desired function.
CS 310 A Few C++ Features, 8 ' $
void inorder (TreeNode* p, void (f )(int&)) { if (p != NULL) { inorder (p->left, f); f (p->data); inorder (p->right, f); } } Alternatively, you can call the function by (f)(p->data);