I want to know your oppinion on this method I though about of defining type generic names. The idea is simply using the preprocessor to generate the names for you. Here's a quick example:
genericstruct.h:
Code:
#include <stdlib.h>
//'SUFIX' and 'TYPE1' required
#define DEFFF(name, subname) name ## subname
#define DEFF(name, subname) DEFFF(name, subname)
#define DEF(name) DEFF(name, SUFIX)
//The declarations
typedef struct DEF(test) DEF(test);
struct DEF(test);
DEF(test) *DEF(createTest)();
TYPE1 *DEF(getElement)(DEF(test) *s, unsigned index);
//The definitions
#ifdef DEF_GENERIC_STRUCT_H
struct DEF(test)
{
TYPE1 elements[10];
};
DEF(test) *DEF(createTest)()
{
DEF(test) *r = malloc(sizeof(DEF(test)));
return r;
}
TYPE1 *DEF(getElement)(DEF(test) *s, unsigned index)
{
return &s->elements[index];
}
#endif
//To avoid redefinition warnings by the pp
#undef TYPE1
#undef SUFIX
genericstruct.c:
Code:
#define DEF_GENERIC_STRUCT
#define TYPE1 int
#define SUFIX _int
#include "genericstruct.h"
#define TYPE1 char
#define SUFIX _char
#include "genericstruct.h"
main.c:
Code:
#include <stdio.h>
#define TYPE1 int
#define SUFIX _int
#include "genericstruct.h"
#define TYPE1 char
#define SUFIX _char
#include "genericstruct.h"
int main(int argc, char **argv)
{
struct test_int *ti = createTest_int();
struct test_char *tc = createTest_char();
*getElement_int(ti, 0) = 100;
*getElement_char(tc, 0) = 'c';
printf("These are the 1st values: %d, %c\n",
*getElement_int(ti, 0),
*getElement_char(tc, 0));
return 0;
}
Of course the organization of this method could use a little work (I'm on it), but I think this can work really well. Of course, this is a very simple example, and I can hopefully find ways of making everything more compact and less confusing. I also couldn't work out a way of generating headers, but I've reached the conclusion I might not have to. Besides that, you could also, of course, put the definitions and declarations in diferent files, that might be nicer to manage.
I want to know however if there are any aparent problems with this method that I might have missed.
I also want to know if this had been thought of before. I've looked around, but seen nothing of the sort, and generic functions and structures seem to be quite an important subject.
Would you ever use this over void*?