I\'m looking for an elegant way to avoid re-writing a function, whose implementation is almost the same, but only the signature (the number of input parameters and their dat
The naive, simple way to do it:
#include
void func_int (int x) { printf("%d\n", x); }
void func_char (char ch) { printf("%c\n", ch); }
#define func(param) \
_Generic((param), \
int: func_int(param), \
char: func_char(param)); \
int main()
{
func(1);
func((char){'A'});
}
This is type safe but only supports one parameter. At a glance this might seem insufficient.
If you want completely variable parameter lists, then you'd have to implement a way to parse variadic macros and __VA_ARGS__
. Likely, it is possible. Likely it is ugly. Likely, this is not what you need.
The need for function overloading in general might be "an XY problem". You need to have functions with different parameter sets and you are convinced that function overloading is the best way to solve it. Therefore you ask how to do function overloading in C. Which is, as it turns out, not necessarily the best way.
A much better way would be to make a function interface with a single struct parameter, which can be adapted to contain all the necessary parameters. With such an interface you can use the above simple method based on _Generic
. Type safe and maintainable.