https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112101
Bug ID: 112101 Summary: feature request: typeof_arg for extracting the type of a function's (or function pointer's) arguments Product: gcc Version: unknown Status: UNCONFIRMED Severity: normal Priority: P3 Component: c Assignee: unassigned at gcc dot gnu.org Reporter: malekwryyy at gmail dot com Target Milestone: --- C23 will add typeof (although gcc had a for a while) which gives the type of an expression or a type. By using it, it is possible to get the return type of a function like so: ``` int func(); typeof(func()) x; // int x; ``` But there's no way to extract the type of the argument of a function: ``` void func(int); ?? x; ``` I think something like 'typeof_arg' would be a good addition. It takes 2 operands, first is function or function pointer, and second is an integer constant for the index of the argument, which must be within [0, arg_count). for example: ``` #define print_func(f) \ printf(#f \ "(" \ _Generic( (__typeof_arg(f, 0)){0}, \ int: "int", \ long: "long", \ float: "float", \ char*: "char*", \ default: "other ") \ ")") ``` this would print a single-argument function's name and arg type like this "puts(char*)". another example: ``` #define gurantee_type(exp, type) \ _Generic(exp, type: exp, default: (typeof(exp)){0}) #define call_with_empty(f) \ _Generic( (__typeof_arg(f, 0)){0}, \ char*: gurantee_type(f, void(*)(char*))(""), \ default: f( (__typeof_arg(f, 0)){0} ) \ ) ``` which calls the function 'f' with empty string if it takes char*, or 0 of the correct type otherwise. this wouldn't work for variadic functions, so __typeof_arg(printf, 1) would be an error. I think a feature like this would be really helpful for generic programming in C