void*
are kind of deprecated for generic programming, there aren't many situations where you should use them nowadays. They are dangerous because they lead to non-existent type safety. And as you noted, you also lose the type information, meaning you'd have to drag around some cumbersome enum
along with the void*
.
Instead you should use C11 _Generic
which can check types at compile-time and add type safety. Example:
#include <stdio.h>
typedef struct
{
int n;
} s_t; // some struct
void func_str (const char* str)
{
printf("Doing string stuff: %s\n", str);
}
void func_s (const s_t* s)
{
printf("Doing struct stuff: %d\n", s->n);
}
#define func(x) _Generic((x), \
char*: func_str, const char*: func_str, \
s_t*: func_s, const s_t*: func_s)(x) \
int main()
{
char str[] = "I'm a string";
s_t s = { .n = 123 };
func(str);
func(&s);
}
Remember to provide qualified (const
) versions of all types you wish to support.
If you want better compiler errors when the caller passes the wrong type, you could add a static assert:
#define type_check(x) _Static_assert(_Generic((x), \
char*: 1, const char*: 1, \
s_t*: 1, const s_t*: 1, \
default: 0), #x": incorrect type.")
#define func(x) do{ type_check(x); _Generic((x), \
char*: func_str, const char*: func_str, \
s_t*: func_s, const s_t*: func_s)(x); }while(0)
If you try something like int x; func(x);
you'll get the compiler message "x: incorrect type"
.