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;
}
With three arguments, the sequence starts at the first value, ends before the second argument and increments or decrements by the third value.
The maximum number of arguments (and corresponding parameters) is 253 for a single function. Arguments are separated by commas. However, the comma is not an operator in this context, and the arguments can be evaluated by the compiler in any order.
Answer 1: When it comes to passing arguments to function, the maximum number of arguments that is possible to pass is 253 for a single function of the C++ programming language.
1 Answer. To explain: C++ allows maximum number of 256 arguments in a function call.
You could use variadic templates:
template <typename T, typename ...Args>
void methodAHelper(T && t, Args &&... args)
{
methodB(t, f(t));
methodAHelper(std::forward<Args>(args)...);
}
void methodAHelper() { }
template <typename ...Args>
void methodA(Args &&... args)
{
// some code
methodAHelper(std::forward<Args>(args)...);
// some other code
}
You can possibly get rid of the &&
and the forwarding if you know that your methodB
call doesn't know about rvalue references, that would make the code a bit simpler (you'd have const Args &...
instead), for example:
methodAHelper(const T & t, const Args &... args)
{
methodB(t, f(t));
methodAHelper(args...);
}
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 to f()
inside the methodB()
. That reduces coupling and interdependence; for example, the entire declaration of f
would only need to be known to the implementation of methodB
. But that's depends on your actual situation.
Alternatively, if there is only one overload of methodB
whose first argument is of type T
, then you could just pass a std::vector<T>
to methodA
and iterate over it:
void methodA(const std::vector<T> & v)
{
// some code
for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)
methodB(*it, f(*it));
// some more code
}
int main() { methodA(std::vector<int>{1,2,3,4}); }
Yes there is, the concept you're looking for is called a variadic function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With