Generic Programs





Genericity in C





Example: Selection Sort

void SelectionSort(int *A, int n) { int i, j, temp ; for (i=0 ; i < n ; i++) { /* Find largest element in remaining array A[i+1, ..., n-1] and store it in A[i]. */ for (j = i+1 ; j < n ; j++) { if (A[i] < A[j] ) { temp = A[i] ; A[i] = A[j] ; A[j] = temp ; } } } }



Generic Selection Sort

void SelectionSort(void *A, int n, int size, CMP_FUNC cmp) ;





Swapping Generic Items

char *temp ; temp = malloc(size) ; ... if (cmp(iptr, jptr) < 0) { bcopy(iptr, temp, size) ; bcopy(jptr, iptr, size) ; bcopy(temp, jptr, size) ; }

If you had to program like this, you would invent a new language too!




Genericity in C: Summary





Genericity in C++





Genericity in C++: Class Derivation





Genericity in C++: Templates