How to create a tuple of N integers in runtime

1.1k views Asked by At

I need a generic way to create a tuple of N integers in runtime where N is the size of a vector (not more than 20). For example:

int main() {
    vector<int> vec;
    vec.push_back(31);
    vec.push_back(24);

    auto x = MakeTuple(vec.size());    // x should have the type tuple<int,int>

    return 0;
}

EDIT: Just to clarify ... I cannot stick to vectors because I need tuple types to create objects of TBB Flow graph template classes using lambda expressions.

EDIT 2: Obviously, I need to explain the problem. I have unstructured meshes which I dynamically partition to X partitions. Each of these partitions is connected with N other partitions, where N > 1. These connections define dependencies between partitions which I need to use to build a flow graph. Since the structure of the mesh is known only in runtime, so is the dependence structure. Thus, I need a way to create specific graph nodes (TBB classes) which take tuples that represent input dependencies as template parameters.

Here is an example how to create a TBB function node that has two input dependencies:

using namespace tbb:flow;

function_node<tuple<int,int> > *f = 
    new function_node<tuple<int,int>>(g, 1, [=] (tuple<int,int> input) -> void { ... });

join_node<tuple<int,int> *j = new join_node<tuple<int,int>> (g);

make_edge(*j, *f);

Now, lets say that we partition the mesh to 10 partitions. We determine dependencies for each partition by checking the list of edges. If there is an edge that connects two partitions, say part1 and part2, then there is a dependency between these partitions. I collect dependency information using per-partition vectors. Now the problem appears: I need to use this dependency information (stored in vectors) to create a graph of function nodes that need proper tuple types based on the number of partition dependencies. For example, if part1 and part2 have following dependencies [2,4,5,9] and [1,3], then I need these two function nodes:

function_node<tuple<int,int> > *f1 = 
    new function_node<tuple<int,int>>(g, 1, [=] (tuple<int,int> input) -> void { ... });

function_node<tuple<int,int,int,int> > *f2 = 
    new function_node<tuple<int,int,int,int>>(g, 1, [=] (tuple<int,int,int,int> input) -> void { ... });
2

There are 2 answers

7
norlesh On

Since it must be a tuple, and you do have a limit on the length then you could use a factory method such as the following psudo code

generic_type MakeTuple(size_t n) {
    switch(n) {
        case 1:
            return make_tuple(int);
        case 2:
            return make_tuple(int, int);
        ...
        default:
            throw 'oh crap';
}
4
Lightness Races in Orbit On

Tuple "dimensions" are part of their type (via templates), and you cannot choose a type at runtime from dynamically-chosen values.

Stick with your vector.