As I understand it, the standard way to implement generic data types in C is with void pointers. However, an alternate approach would be to use macros. Here’s an example implementation of a generic “Option” type using macros:
#define OPTION(T)
struct option_##T {
bool exists;
T data;
};
typedef struct option_##T option_##T;
bool is_some(option_##T x) { return x.exists; }
bool is_none(option_##T x) { return !x.exists; }
OPTION(int);
int main(int argc, char *argv[]) {
option_int x = {.exists = true, .data = 3};
}
This has the benefit of avoiding an extra layer of indirection that would be present with a void * implementation, possibly at the cost of binary size. Is there a reason this technique is not used often?