Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array of unknown rank by reference

I am trying to pass by reference an array of unknown number of dimensions (rank). Basically, I'd like to do something like this (which does not compile)

template <typename T, int... dims>
void f(T (&arr)[dims]...) // not working
{
    // would like to modify the elements of `arr` here, according to some rule
}

int main()
{
    int arr[2][3][4]; // rank 3
    f(arr);
}

Is there any way of achieving this? In particular, is it somehow possible to use a variadic-template approach?

I can do the generic template<typename T> f(T& arr), but in this case how I'd be able to recover the sizes without explicitly passing them? (Even with a variadic template approach I'm not sure how to recover the individual elements in the pack... without some kind of recursive folding).

In particular, I'm looking for a simple way of initializing an unknown-rank array according to some rule.

like image 257
vsoftco Avatar asked Apr 02 '15 17:04

vsoftco


1 Answers

You just pass an reference to array of type T. Then T can be another array and so on. No need for complex syntax. So your code will look like this:

template <typename T, int sz>
void f(T (&arr)[sz]) // working
{
    std::rank<T[sz]>::value; //evaluates to array rank
}

int main()
{
    int arr[2][3][4]; // rank 3
    f(arr);
}

You can then get the array rank by using std::rank.

And you can get sub-array sizes by using std::remove_extent and template recursion.

Life example.

like image 156
AnArrayOfFunctions Avatar answered Oct 23 '22 01:10

AnArrayOfFunctions