Va_args process in c ++

I have a function A(...) and B(...) . Now I need to call B inside A , any methods to pass this ... from A to B ? Pseudocode:

 void A(...) { // Some operators B(...); // Instead of ... I need to pass A args } 

ps I know that this can be done with macros, but what about functions.

+6
source share
3 answers

You cannot redirect va_args. You can redirect only va_list.

 void vB(int first, va_list ap) { // do stuff with ap. } void B(int first, ...) { va_list ap; va_start(ap, first); vB(first, ap); va_end(ap); } void A(int something_else, int first, ...) { va_list ap; va_start(ap, first); vB(first, ap); // <-- call vB instead of B. va_end(ap); } 

(This also means that there are functions like vprintf .)


If you are using C ++ 11, you can do this with variable templates with perfect forwarding:

 template <typename... T> void A(T&&... args) { B(std::forward<T>(args)...); } 
+7
source

Unfortunately, you cannot take va-list and pass it to a function that takes a list of variable arguments. The syntax does not allow you to expand the va_args structure back into parameters.

You can pass it as va_list in one parameter, so one of the solutions should be to define a function that does the work with va_list . You can then define another function by wrapping it using an argument list, which can then pass va_list to the main function and pass the return value back. You see this type of template in the C standard library with printf() and vprintf() and similar pairings.

+2
source

You need to slightly change the signature of your methods. I assume you want to do something like this:

 void B(int numParams, va_list parameters) { // Your code here. Example: for (int i=0; i<numParams; i++) { // Do something using va_arg to retrieve your parameters } } void A(int numParams, ...) { va_list parameters; va_start(parameters, numParams); B(numParams, parameters); va_end(parameters); } 
+1
source

Source: https://habr.com/ru/post/908706/


All Articles