Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to generate a tuple given a size N and a type T

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:

  • the number of the parameters is not given
  • the types are all the same, but unknown (even if they must be default constructible)

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.

like image 780
skypjack Avatar asked May 07 '16 21:05

skypjack


People also ask

How to create a tuple with numbers in Python?

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.

How to assign the value of two existing tuples to a new 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.

How do you create a tuple with no items in it?

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.

What are immutable tuples in Python?

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.


Video Answer


1 Answers

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>{}); } 
like image 72
T.C. Avatar answered Oct 13 '22 18:10

T.C.