added generics example

This commit is contained in:
Richard Thier 2025-04-26 00:41:51 +02:00
parent 2a45772420
commit c874e0fb9e

View File

@ -45,6 +45,41 @@ RAII (with scope closing destructors in reverse order):
creat(Vektor, data, &n); creat(Vektor, data, &n);
printf("data.count:%d\n", data.count); printf("data.count:%d\n", data.count);
## Generics
Generic array using handle.h
#include <stdlib.h>
#include "handle.h"
/* Generic array macro */
#define Array(T,AT) struct AT { \
size_t count; \
T *v; \
}; handle(AT) { \
if(state == HANDLE_CREAT) { \
self->count = *(size_t*) data; \
self->v = (T*) calloc(self->count, sizeof(T)); \
} else if (state == HANDLE_DESTR){ \
if(self->v) free(self->v); \
} \
}
Usage:
#include "array.h"
Array(uint64_t, Array_uint64);
int main() {
size_t n = 0;
printf("Number of elements to sum: ");
scanf(" %zu", &n);
/* Create a 64 bit array of 'n' elements named 'data' */
creat(Array_uint64, data, &n);
...
}
## Compatibility ## Compatibility
Ok this might be pain for you but this works only with gcc... Ok this might be pain for you but this works only with gcc...