To all of you C++ programmers (I'm one too), you can use pseudo-templates in C, using generic pointers and the memcpy function. I think the correct term is generic functions in C.
For instance, say you want to swap two values of arbitrary data-type. You would do something like this in C++:
Code: Select all
#include <iostream>
#include <cstdlib>
template<typename T>
void swap(T &a, T &b);
int main(void)
{
int a = 10, b = 20;
swap(a, b);
std::cout << "a: " << a << " and b: " << b << std::endl;
return EXIT_SUCCESS;
}
template<class T>
void swap(T &a, T &b)
{
T tmp = a;
a = b;
b = tmp;
}
Code: Select all
#include <stdio.h>
#include <stdlib.h>
void swap(void *a, void *b, int n);
int main(void)
{
int a=0, b=10;
swap(&a, &b, sizeof(int));
printf("a: %d, b: %d", a, b);
return EXIT_SUCCESS;
}
void swap(void *a, void *b, int n)
{
void *buffer = malloc(n);
memcpy(buffer, a, n);
memcpy(a, b, n);
memcpy(b, buffer, n);
free(buffer);
}
Just remember that you can not dereference void*'s and you'll be alright This works better than templates in that, it works in analogue to an inline functions, internally at the asm level. With C++ templates, if you have a huge amount of different types (including user-defined types i.e. classes) using template functions, the implementations would expands per-type. Whereas, with generic C functions, you only have this one representation for the implementation of swap.
So those are my two cents