C ++ 11: the number of parameters to a Variadic template function?

How can I get the number of arguments to a variational pattern function?

t

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?

+50
c ++ c ++ 11 variadic-functions variadic-templates
Aug 19 '12 at 4:50
source share
1 answer

Just write this:

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

Note that n is a constant expression (known at compile time), which means you can use it where a constant expression is required, for example:

 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 calculate the aggregated size of packed types (as opposed to the number of types in a package), then you should 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 the following:

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

Hope this helps.

+63
Aug 19 '12 at 5:00
source share



All Articles