How do I split variadic template arguments in two halves? Something like:
template <int d> struct a {
std::array <int, d> p, q;
template <typename ... T> a (T ... t) : p ({half of t...}), q ({other half of t...}) {}
};
How do I split variadic template arguments in two halves? Something like:
template <int d> struct a {
std::array <int, d> p, q;
template <typename ... T> a (T ... t) : p ({half of t...}), q ({other half of t...}) {}
};
Here is yet another solution:
I know this question is quite old, but I found it only yesterday while looking for a solution to a very similar problem. I worked out a solution myself and ended up writing a small library which I believe does what you want. You can find a description here if you are still interested.
Luc's solution is clean and straightforward, but sorely lacks fun.
Because there is only one proper way to use variadic templates and it is to abuse them to do crazy overcomplicated metaprogramming stuff :)
Like this :
It is quite short, except that we need to code some helper :
First we need the structure make_pack_indices, which is used to generate a range of integer at compile-time. For example
make_pack_indices<5, 0>::type
is actually the typepack_indices<0, 1, 2, 3, 4>
We also need a get() function, very similar to std::get for tuple, such as
std::get<N>(ts...)
return the Nth element of a parameters pack.But to build get() we also need a pack_element helper structure, again very similar to std::tuple_element, such as
pack_element<N, Ts...>::type
is the Nth type of the parameters pack.And here we go.
Actually I don't really understand why pack_element and get() are not in the standard library already. Those helpers are present for std::tuple, why not for parameters pack ?
Note : My implementation of pack_element and make_pack_indices is a direct transposition of std::tuple_element and __make_tuple_indices implementation found in libc++.
Note that in this particular case, you may use
std::initializer_list
:We still lack a lot of helpers to manipulate variadic parameter packs (or I am not aware of them). Until a nice Boost library bring them to us, we can still write our own.
For example, if you are willing to postpone your arrays initialization to the constructor body, you can create and use a fonction that copies part of the parameter pack to an output iterator:
As you can see, you can (not so) easily create your own algorithms to manipulate parameter packs; all is needed is a good understanding of recursion and pattern matching (as always when doing Template MetaProgramming...).