POP! (That's a brain explosion)
What? In C, you'd have a swap function to swap two integers, so that (1, 2) would become (2,1):
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
But if you wanted to have a library of swap functions for different datatypes, you'd need to implement swap_int(), swap_long(), swap_float(), swap_string(), and so on. Plus, any data types that you defined yourself.
void swap_string(char **a, int **b) {
char * temp;
temp = *a;
*a = *b;
*b = temp;
}
C++ would make this somewhat easier, because you can have 'function overloading", where the same function name with different arguments results in separate code:
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void swap(char **a, int **b) {
char * temp;
temp = *a;
*a = *b;
*b = temp;
}
(now, the top-level code can say "swap(a,b)" for several types of a and b.)
But - note that the actual CODE in those functions stays the same regardless of the types of arguments, except for the type specifications in the header and for "temp"; what you really want, so you can avoid rewriting the same code over and over, is to somehow pass that part of the function - the type - as an argument to some sort of macro. (I could almost imagine this as a C preprocessor macro, at least for an inline swap. But... Ugly!)
template <typename my_type>
void swap(my_type *a, my_type *b)
{
my_type temp;
temp = *a;
*b = *a;
*b = temp;
}
This is what C++ templates give you. (one of the things they give you, anyway.) It's made more useful by also providing a "Standard Template Library" (STL) that provides a lot of common data structures and algorithms. So you can SORT your VECTOR of (user-defined) THING_TYPES without having to write any code for SORT, or VECTOR (a growable array-like thing) that is specific to THING_TYPE (other than a "compare-to" function.) (again, you can almost do this in C, given (dangerous) void* pointers, macros, and so on. But the C++ version is much prettier and less subject to being wrong.)