Perhaps another option would be to turn the entire implementation into a macro, so you can create all the "instantiations" that you want.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#define USE_VECTOR_OF(type) \
typedef struct \
{ \
int length; \
type* buffer; \
} vector_##type; \
\
vector_##type create_vector_##type(void) \
{ \
vector_##type vec = {0, 0}; \
return vec; \
} \
\
int add_##type(vector_##type* vec, type value) \
{ \
type* p = realloc(vec->buffer, vec->length * sizeof(type)); \
if (p) { \
vec->buffer = p; \
vec->buffer[vec->length] = value; \
++vec->length; \
return 1; \
} \
return 0; \
} \
\
type get_##type(const vector_##type* vec, int index) \
{ \
assert(index >= 0 && index < vec->length); \
return vec->buffer[index]; \
}
#define Vector(type) vector_##type
#define Vcreate(type) create_vector_##type()
#define Vadd(type, vec, val) add_##type(vec, val)
#define Vget(type, vec, index) get_##type(vec, index)
USE_VECTOR_OF(int)
USE_VECTOR_OF(double)
int main(void)
{
{
Vector(int) vec = Vcreate(int);
if (!Vadd(int, &vec, 42)) return -1;
if (!Vadd(int, &vec, 100)) return -1;
printf("added: %d %d\n", Vget(int, &vec, 0), Vget(int, &vec, 1));
}
{
Vector(double) vec = Vcreate(double);
if (!Vadd(double, &vec, 15.75)) return -1;
if (!Vadd(double, &vec, -21.123)) return -1;
printf("added: %f %f\n", Vget(double, &vec, 0), Vget(double, &vec, 1));
}
return 0;
}