Is it possible for a class to have a member which is a multidimensional array whose dimensions and extents are not known until runtime?
I have found (via this guide) a way to create a struct to easily nest std::arrays at compile time using template metaprogramming:
#include <array>
/*
this struct allows for the creation of an n-dimensional array type
*/
template <typename T,size_t CurrentDimExtent,size_t... NextDimExtent>
struct MultiDimArray{
public:
//define the type name nestedType to be a recursive template definition.
using nestedType=typename MultiDimArray<T,NextDimExtent...>::type;
using type=std::array<nestedType,CurrentDimExtent>;
};
/*
This struct is the template specialization which handles the base case of the
final dimensional extent
*/
template <typename T,size_t DimExtent>
struct MultiDimArray<T,DimExtent>{
using type=std::array<T,DimExtent>;
};
this still falls short of satisfying my requirement in two ways (that I know of):
- In order to declare a variable (or a pointer to a variable) of this type you must state the dimensions.
- This only works when the DimExtents are constant expressions (set at compile time).
To demonstrate why number 2 is a distinct problem, here is a class with a set number of dimensions (2) using a void* to reference the multidimensional array:
template <typename T>
class TwoDimGrid{
public:
TwoDimGrid(const size_t extent1,const size_t extent2):
_twoDimArray(new MultiDimArray<T,extent1,extent2>);
private:
void* _twoDimArray;
};
This will not compile as extent1 and extent2 are not constant expressions.
other notes:
- I would like to see if it's possible to accomplish using std:array, rather than native arrays or a dynamically resizing container like std::vector.
- Please use smart pointers where appropriate (I didn't as I'm not really sure how to handle a smart void pointer).
Edit
I have fallen into the trap of The XY Problem with X being the first sentence of this question and Y being how to accomplish it with std::array. I therefore created a new question and am leaving this one here in case it's ever possible to solve Y problem.
old school multidimensional arrays, something along these lines: