(The question was originally tagged both C and C++; the C tag was later removed. Part of the following is specific to C, but I'm leaving it here in case it's useful to others.)
In C, no, I don't believe it's possible to do this with compile-time checking. Variadic functions (a) require at least one fixed parameter (eliminating your func()
example), and (b) do not check the types of the variadic arguments at compile time. Variadic macros (new in C99) might be more promising, but they perform no type checking. I've thought about how to do this with nested generic selections (a new feature in C11, nonexistent in C++), but I don't believe they can solve the problem.
If you're using C (this question was originally tagged both C and C++), I think the closest you can get is to have a distinct function for each number of parameters:
void func0(void);
void func1(char*, int, char);
void func2(char*, char*, int, int, char, char);
void func3(char*, char*, char*, int, int, int, char, char, char);
You know when you're writing the call how many parameters you're passing, so specifying a different function isn't too much of a burden.
In C++, you could provide multiple overloaded functions, each of which takes arguments of the appropriate types:
void func();
void func(char*, int, char);
void func(char*, char*, int, int, char, char);
void func(char*, char*, char*, int, int, int, char, char, char);
And so on, for as many overloadings as you have patience for.
Neither of these solutions is indefinitely scalable to an arbitrary number of arguments.
I had thought that there's no general solution in C++, but Jarod42's answer (which I haven't yet taken the time to understand) appears to have shown otherwise. On the other hand, there's something to be said for simplicity. On the other other hand, you only have to write it once.
One more thing: your last example is:
func('a',2) //error 0 string 1 char 1 int
In C, both 'a'
and 2
are of the same type, namely int
. In C++, a
is of type char
. (Again, this isn't necessarily relevant if you're only concerned with C++.)