This below code from user Faheem Mitha, is based on user Johannes Schaub - litb's answer in this SO. This code perfectly does what I seek, which is conversion of a tuple
into parameter pack, but I don't understand this code well enough and therefore I thought I will create a new discussion that might help template metaprogramming newbies like me. So, please pardon the duplicate posting.
Now moving onto the code
#include <tuple>
#include <iostream>
using std::cout;
using std::endl;
template<int ...> struct seq {};
template<int N, int ...S> struct gens : gens<N - 1, N - 1, S...> { };
template<int ...S> struct gens<0, S...>{ typedef seq<S...> type; };
double foo(int x, float y, double z)
{
return x + y + z;
}
template <typename ...Args>
struct save_it_for_later
{
std::tuple<Args...> params;
double(*func)(Args...);
double delayed_dispatch()
{
return callFunc(typename gens<sizeof...(Args)>::type()); // Item #1
}
template<int ...S>
double callFunc(seq<S...>)
{
return func(std::get<S>(params) ...);
}
};
int main(void)
{
std::tuple<int, float, double> t = std::make_tuple(1, (float)1.2, 5);
save_it_for_later<int, float, double> saved = { t, foo };
cout << saved.delayed_dispatch() << endl;
return 0;
}
I'm completely confounded by Item #1 above:
- What purpose does
typename
serve on that line? - I understand that
gens<sizeof...(Args)>::type()
will expand togens<3>::type()
, but that doesn't seem to match neithertemplate<int N, int ...S> struct gens : gens<N - 1, N - 1, S...> { };
nortemplate<int ...S> struct gens<0, S...>
. I'm obviously missing the point and I'd be glad if someone can explain what is happening here.
I do understand that callFunc
gets invoked in this form callFunc(seq<0,1,2>)
and the return statement of this method itself expands to return func(std::get<0>(params), std::get<1>(params), std::get<2>(params)
and this is what makes this scheme work, but I cannot workout how this seq<0,1,2>
type is generated.
Note: Using std::index_sequence_for
is not an option, my compiler doesn't support C++14 features.
PS: Can this technique be classified as template metaprogramming?