lundi 18 décembre 2017

Function with a fixed amount of parameters determined by an integer

I have a class with a template that accepts an integer:

template <unsigned int N>
class Example {};

I'm looking for a way to define a (member)function that accepts some amount of Example objects as arguments. The amount is to be determined by N, so the function would be used like this:

Function(Example<2>(), Example<2>());
Function(Example<3>(), Example<3>(), Example<3>());

What I tried so far:

Using an initializer list, one is able to pass a set of objects to the function:

template <unsigned int N>
void Function(std::initializer_list<Example<N>> list);
//...
Function({Example<2>(), Example<2>()});

However, the problem besides the fact that really only one argument is passed(the list), is that with this method any number of arguments can be used:

Function({Example<2>()});

I also tried using a variadic function:

template <unsigned int N>
void Function(Example<N> e...)
{
    va_list args;
    va_start(args, e);
    //...
}
Function(Example<2>(), Example<2>());

This makes it possible to use real parameters, but the problem of using any number of arguments remains, and it's not possible to know how many arguments were actually passed.

Aucun commentaire:

Enregistrer un commentaire