I've been looking into how to declare functions or class members with a variable number of argument, and came across variadic functions, however I was wondering if there was some way to access the number of arguments pass to the function, without having to pass it directly as a first argument, as most of the documentation presents. I am also aware that I can use either variadic templates or std::initializer_list
, but since I was looking to pass multiple arguments of the same type, those seem both too generic and/or with a convoluted syntax.
#include <cstdarg>
bool func(int args...) {
va_list list;
va_start(list, args);
int val = args;
while(val >=0) {
std::cout << val << std::endl;
val = va_arg(list, int);
}
return true;
}
bool other_func(int c, int args...) {
va_list list;
va_start(list, args);
int val = args;
for (int i = 0; i<c; i++) {
std::cout << val << std::endl;
val = va_arg(list, int);
}
return true;
}
int main(int argc, char const *argv[]) {
func(2, 7, 47, -1, 23 /* ignored */);
other_func(3 /* n of parameters */, 2, 7, 47);
return 0;
}
In these particular example, func
loops over the input arguments until a negative value is found (in order to illustrate the issue and force a stop flag) while other_func
requires the number of arguments to be passed as the first argument. Both these implementations seemed to me rather flawed and unsafe, is there a better way to approach this?
Aucun commentaire:
Enregistrer un commentaire