I want to do identical processing to a bunch of arguments of a function. Is there a way to loop over all arguments ? I am doing it the way represented in following code, but want to see if there is a compact way to do this.,
void methodA(int a1, int a2, int b1, double b2){
//.. some code
methodB(a1, f(a1));
methodB(a2, f(a2));
methodB(b1, f(b1));
methodB(b2, f(b2));
// more code follows ...
}
int f(int a){
// some function.
return a*10;
}
double f(double b){
return b/2.0;
}
You could use variadic templates:
You can possibly get rid of the
&&and the forwarding if you know that yourmethodBcall doesn’t know about rvalue references, that would make the code a bit simpler (you’d haveconst Args &...instead), for example:You might also consider changing
methodB: Since the second argument is a function of the first argument, you might be able to only pass the first argument and perform the call tof()inside themethodB(). That reduces coupling and interdependence; for example, the entire declaration offwould only need to be known to the implementation ofmethodB. But that’s depends on your actual situation.Alternatively, if there is only one overload of
methodBwhose first argument is of typeT, then you could just pass astd::vector<T>tomethodAand iterate over it: