1 Problem Introduction
First, introduce a problem to implement a generic swap function, using C + + and C implementations, respectively.
2 generics for C + +
C + + has a good generic programming mechanism, so I quickly wrote the C + + version of the generic swap function.
Template<typename t>void Myswap (t &a, t &b) {T c = a;a = B;b = C;}3 C-Language generics
My first idea is that since you can't exchange variables directly (type doesn't know), then swap pointers. Next moment, I would like to slap myself! Is it an lvalue, and you exchange pointers? stupid!
Then pass in one more parameter, pass in the size, then we can exchange the memory directly according to the size. Good idea:
void Myswapc (void* A, void *b, int size) {void *p = (void*) malloc (size); assert (P! = NULL); memcpy (P, a, size); memcpy (A, B, s ize); memcpy (b, p, size);}4 Summary
Using certain skills, C language can also achieve a certain function of generic programming, but when programming must be more careful, C language generic programming is not perfect, and there is not enough type check, so it is easy to error.
C-language generic programming