Download Templates - Data Structures - Notes | CS 310 and more Study notes Data Structures and Algorithms in PDF only on Docsity! CS 310 A Few C++ Features, 1' & $ % Templates 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? • Solution 1: copy and modify. • Solution 2: let the machine do the tedious job; use templates. CS 310 A Few C++ Features, 2' & $ % Example 1: A Template Swap Function // No machine instructions generated here. The compiler // merely memorizes the template of swap functions. template <class T> void swap (T& x, T& y) { T tmp=x; x = y; y = tmp; } 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, 3' & $ % Pointer to Functions • A function name in a C++ program is actually an address – the starting address of the machine instructions of the functions. • You can store such an address in a pointer, called function pointers. • Example double sin(double x) { ... computate sin(x) ... } double cos(double x) { ... computate cos(x) ... } 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) }