C ++ varargs / variadic with two types of arguments

I am trying to implement a variational function. I searched the Internet and found that most examples handle only one type of argument (e.g. calculating the average of integers). In my case, the type of the argument is not fixed. It can include either char *, int, or both at the same time. Here is the code I ended up in:

void insertInto(int dummy, ... ) {
   int i = dummy;
   va_list marker;
   va_start( marker, dummy );     /* Initialize variable arguments. */
   while( i != -1 ) {
      cout<<"arg "<<i<<endl;
             /* Do something with i or c here */
      i = va_arg( marker, int);
      //c = va_arg( marker, char*);
   }
   va_end( marker );              /* Reset variable arguments.      */

Now this will work if I only need to deal with integers, but as you can see, I have the variable char * c in the comments, which I would like to use if the argument is char *.

So the question is how to handle the return value of va_arg without knowing whether it is int or char *?

+3
source share
5 answers

++, C-.

,

  class Inserter
  {
  public:
      Inserter& operator()( char const* s )
      {
          cout << s << endl;
          return *this;
      }

      Inserter& operator()( int i )
      {
          cout << i << endl;
          return *this;
      }
  };

Inserter()( "blah" )( 42 )( "duh" )

, .

hth.,

+10

, , va_arg, , int char *?

. . - . printf :

printf("%s %i\n", "Hello", 123);  // works
printf("%s %i\n", 123, "Hello");  // also valid (though most modern compiles will emit a warning), but will produce garbage or crash
+3

- . , printf , . , .

+2

http://en.wikipedia.org/wiki/Variadic_function#Variadic_functions_in_C.2C_Objective-C.2C_C.2B.2B.2C_and_D:

In some other cases, such as printf, the number and types of arguments are calculated from the format. In both cases, it depends on the programmer to actually enter the correct information.

So, for processing several types insertInto(), the concept of the format string type is required.

0
source

You can make the processing conditional for a dummy parameter. I have routines that take an action argument and handle the arguments differently based on the action

For instance:

int i; char *c;
switch(dummy) {
    case 1:
        i = va_arg(marker, int);
        // do something with i
        break;
    case 2:
        c = va_arg(market, char *);
        // do something with c
        break;
}
0
source

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


All Articles