Suppose I have a template which is parametrized by a class type and a number of argument types. a set of arguments matching these types are stored in a tuple. How can one pass these to a constructor of the class type?
In almost C++11 code:
template<typename T, typename... Args>
struct foo {
tuple<Args...> args;
T gen() { return T(get<0>(args), get<1>(args), ...); }
};
How can the ...
in the constructor call be filled without fixing the length?
I guess I could come up with some complicated mechanism of recursive template calls which does this, but I can't believe that I'm the first to want this, so I guess there will be ready-to-use solutions to this out there, perhaps even in the standard libraries.
Create a sequence of indexes from 0 through n-1:
unpack them in parallel with your args, or as the index to
get<>
in your case.The goal is something like:
use
repack
in yourgen
like this:You'll need to use the indices trick, which means a layer of indirection:
You need some template meta-programming machinery to achieve that.
The easiest way to realize the argument dispatch is to exploit pack expansion on expressions which contain a packed compile-time sequence of integers. The template machinery is needed to build such a sequence (also see the remark at the end of this answer for more information on a proposal to standardize such a sequence).
Supposing to have a class (template)
index_range
that encapsulates a compile-time range of integers [M, N) and a class (template)index_list
that encapsulates a compile-time list of integers, this is how you would use them:And here is a possible implementation of
index_range
andindex_list
:Also notice, that an interesting proposal by Jonathan Wakely exists to standardize an
int_seq
class template, which is something very similar to what I calledindex_list
here.C++14 will add standard support for
index_sequence
: