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.
You just pass an reference to array of type
T
. ThenT
can be another array and so on. No need for complex syntax. So your code will look like this: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.