Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 885
Jannis Avatar asked Dec 18 '17 10:12

Jannis


People also ask

What is an integer parameter?

Integer parameters define integer values that are used as inputs for some LiveCompare actions.

What are the parameters of a function called?

The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.

Which type is used to store the arguments when the number of arguments for a function is not constant in C?

Variable length argument is a feature that allows a function to receive any number of arguments.

How many parameters does a function have?

The main function can be defined with no parameters or with two parameters (for passing command-line arguments to a program when it begins executing). The two parameters are referred to here as argc and argv, though any names can be used because they are local to the function in which they are declared.


1 Answers

Assuming you want the number of arguments to be deduced from the Example<N> type, and that all Example<I> should share the same such N, a C++17 solution might be

template <unsigned int... I>
auto Function( Example<I>... ) ->
    std::enable_if_t<( ( I == sizeof...(I) ) && ... )>
{
   // or static_assert() if you always want an error
}
like image 169
Massimiliano Janes Avatar answered Oct 05 '22 15:10

Massimiliano Janes