A
A
artemmensk2014-05-18 20:49:37
C++ / C#
artemmensk, 2014-05-18 20:49:37

Variable number of parameters and function template

I have a template class that implements a matrix (cells can contain data of different types).
to fill the matrix, the function is used:

void setItems(int _row, int _col, ...){

    fieldInitialization(_row, _col);

    int argumentNumber = _row * _col;
    va_list arguments;
    va_start(arguments, argumentNumber);
    for (int i = 0 ; i < _row ; i++){
      for (int j = 0 ; j < _col ; j++){
        tab[i][j] = va_arg(arguments, T);
      }
    }
    va_end(arguments);
  }

The compiler warns:
second parameter of ‘va_start’ not last named argument [enabled by default]

and
- ‘char’ is promoted to ‘int’ when passed through ‘...’ [enabled by default]
  - (so you should pass ‘int’ not ‘char’ to ‘va_arg’)
  - if this code is reached, the program will abort

When filling with ints, everything is OK,
as soon as I switch to char, the program stops as the compiler warned :(
I ask for tips / help on how to implement the extraction of arguments in advance without knowing the type.
ps The task is educational, therefore, for example, you can’t use specialization.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
malerix, 2014-05-18
@artemmensk

It seems to me that there is an error here:
va_start(arguments, argumentNumber);
The second argument to the va_start macro is the last known argument in the function. The compiler even tells you about it.
For example:

int magicFunction(int a, int b, int c, ...) {
    va_list args;
    va_start(args, c);
   //...
}

Therefore, you should write it like this:
By the way, if you have the opportunity to use a debugger, look at the stack when calling this function, and compare the addresses where argumentNumber and _col are located. So the first option (c int) is also non-working.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question