C ++ is interesting: execute a separate function for each parameter in the Variable Parameter template. The parameter Template
For Variable Parameter templates that appear after c ++ 11, we generally process all the parameters in a unified manner. When you need to perform different operations for each parameter or call different functions, the syntax is not directly supported.
Variable Parameter template syntax:
template<typename...T>void function(T...args){}
If you want to execute a function for each parameter indicated by args separately, you can use the following method:
void print(int arg){}template <typename... T>void callfn(void(*fn)(T...args)){ using expand_type = int[]; expand_type{ (print(args), 0)... };}void fn1(int a1, int a2, int a3){}void fn2(int a1, int a2, int a3, int a4, int a5, int a6){}int main(){ callfn(fn1); callfn(fn2); return 0;}
In this way, the print function can be called once for each parameter of the function passed in by callfn.
We should first think of using this method.
print(args);...
However, the syntax does not work. Fortunately, we can use the initialization list Syntax:
using expand_type = int[];expand_type{ (print(args), 0)... };
(Print (args), 0) 0 is used to generate a positive number for the brackets, so that the initialization list is legal.
Reference 1: https://stackoverflow.com/questions/17339789/how-to-call-a-function-on-all-variadic-template-args