Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Variadic Function Templates of Known Type

I'm currently trying to get my head around some of the things I can do with variadic template support. Let's say I have a function like this -

template <typename ... Args>
void foo(Args ... a)
{
    int len = sizeof...(tail);
    int vals[] = {a...};
    /* Rest of function */
}

/* Elsewhere */
foo(1, 2, 3, 4);

This code works because I assume beforehand that the arguments will be integers, but obviously will fail if I provide something else. If I know that the parameter packs will contain a particular type in advance, is there some way that I can do without the templating and have something like -

void foo(int ... a)

I have tried doing this, but the compiler gave an error about foo being a void field. I know that I can also access the parameters in the pack through recursion, but I'm not sure this will fix the problem that I have - namely I want to be able to take a variable number of arguments of the same type.

like image 942
znby Avatar asked Jul 22 '13 15:07

znby


People also ask

What is a variadic template C++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.

What is variadic function in C?

Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.

How do you access variadic arguments?

To access variadic arguments, we must include the <stdarg. h> header.

How do you expand a parameter pack?

Parameter packs can only be expanded in a strictly-defined list of contexts, and operator , is not one of them. In other words, it's not possible to use pack expansion to generate an expression consisting of a series of subexpressions delimited by operator , .


1 Answers

This should work:

void foo(int);

template<typename ...Args>
void foo(int first, Args... more)
{
   foo(first);
   foo(more...);
}
like image 137
Yong Avatar answered Oct 12 '22 12:10

Yong