In c++, how can I implement a function with an int template argument indicating the tuple length and produce a std::tuple with that length?
E.g.
func<2>() returns std::tuple<int, int>();
func<5>() returns std::tuple<int, int, int, int, int>().
In c++, how can I implement a function with an int template argument indicating the tuple length and produce a std::tuple with that length?
E.g.
func<2>() returns std::tuple<int, int>();
func<5>() returns std::tuple<int, int, int, int, int>().
Here is a recursive solution with alias template and it's implementable in C++11:
For example if we want
"tuple of 3 doubles"
we can write:If you're okay with a C++14 solution, Ryan's answer is the way to go.
With C++11, you can do the following (still based on
index_sequence
, but that's implementable in C++11):With that:
Using an
index_sequence
and a helper type alias you can generate the type you want:It is worth calling out that in the general case you would probably be better with a
std::array
, (in your case you can't use one), but astd::array
can behave like a tuple, similarly to astd::pair
.Update: since you've made it clear you're working with c++11 and not 14+, you'll need to get an implementation of
index_sequence
and related from somewhere (here is libc++'s). Here is the C++11 version offunc
andfunc_impl
with explicit return types:Here are two boost.hana solutions (C++14):
Both produce integer-tuples of size 2, but instead of
std::tuple
s they yieldhana::tuple
s.The plain old recursion is your friend: