While trying to reply to this question, I found my self in the need of creating a bunch of parameters for a variadic function on the fly where:
At runtime, the standard containers and a for loop can be used to do that.
Anyway, I'd like to generate a set of parameters at compile time, so as to be able to forward them to a variadic function.
Because of that, a std::tuple
seemed the obvious solution.
Here arose the question: given a size N
and a default constructible type T
at compile time, how can I write a function to generate a tuple of the given size?
I'm looking for something like this:
auto tup = gen<MyType, N>();
On SO is a notable example of a recursive generator based structs but I was struggling with a function based solution and I've not been able to find it anywhere.
Write a Python Program to Create a Tuple with Numbers or numeric tuple. The first one will create a tuple with 22 as a value. In this Python program, we created an empty tuple, and it allows the user to enter the tuple items. Within the loop, we are concatenation each numeric tuple item to an already declared tuple.
Here, we assign the value of two existing tuples to a new tuple by using the ‘ +’ operator. In python, to check if the specified element is present in the tuple we use the ” in “ keyword to check and if the element is not present then it will not return anything.
To create a tuple in Python, add items with round brackets “ ()” like my_tuple = (“red”, “blue”, “green”) and to create an empty tuple, use empty round brackets ” () ” with no items in it.
These immutable tuples are a kind of group data type. Moreover, we access elements by using the index starting from zero. There are some functions that we can directly perform in a tuple. Let us learn these tuple functions in detail. There are some methods and functions which help us to perform different tasks in a tuple.
A correctly written forwarding function (a la std::apply
) should work with std::array<T, N>
and anything else that implements the std::tuple_size
/std::get
interface. That said,
template<size_t, class T>
using T_ = T;
template<class T, size_t... Is>
auto gen(std::index_sequence<Is...>) { return std::tuple<T_<Is, T>...>{}; }
template<class T, size_t N>
auto gen() { return gen<T>(std::make_index_sequence<N>{}); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With