Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11: Number of Variadic Template Function Parameters?

How can I get a count of the number of arguments to a variadic template function?

ie:

template<typename... T> void f(const T&... t) {     int n = number_of_args(t);      ... } 

What is the best way to implement number_of_args in the above?

like image 625
Andrew Tomazos Avatar asked Aug 19 '12 04:08

Andrew Tomazos


People also ask

Can variadic methods take any number of parameters?

A variadic function allows you to accept any arbitrary number of arguments in a function.

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.


1 Answers

Just write this:

const std::size_t n = sizeof...(T); //you may use `constexpr` instead of `const` 

Note that n is a constant expression (i.e known at compile-time), which means you may use it where constant expression is needed, such as:

std::array<int,   n>  a; //array of  n elements std::array<int, 2*n>  b; //array of (2*n) elements  auto middle = std::get<n/2>(tupleInstance); 

Note that if you want to compute aggregated size of the packed types (as opposed to number of types in the pack), then you've to do something like this:

template<std::size_t ...> struct add_all : std::integral_constant< std::size_t,0 > {};  template<std::size_t X, std::size_t ... Xs> struct add_all<X,Xs...> :    std::integral_constant< std::size_t, X + add_all<Xs...>::value > {}; 

then do this:

constexpr auto size = add_all< sizeof(T)... >::value; 

In C++17 (and later), computing the sum of size of the types is much simpler using fold expression:

constexpr auto size = (sizeof(T) + ...); 

Hope that helps.

like image 57
Nawaz Avatar answered Oct 19 '22 08:10

Nawaz