15

In the C++0x Variadic Templates Proposal paper Link there is an example of a class which supports an arbitrary number of dimensions. I have copied it below:

template<typename T, unsigned PrimaryDimension, unsigned... Dimensions>
class array { /* implementation */ };

array<double, 3, 3> rotation matrix; // 3x3 rotation matrix

Sadly the implementation is not provided. As I am relatively new to variadic templates I would be interested to see an implementation of this container.

Thanks to anybody who can provide a simple implementation.

Community
  • 1
  • 1
Ricky65
  • 1,657
  • 18
  • 22

1 Answers1

29

Here is a very simple implementation (compiled with gcc4.6.1) that demonstrates the recursion involved in getting the array type right - if there is some other specific implementation detail you are interested in, please let us know:

template<class T, unsigned ... RestD> struct array;

template<class T, unsigned PrimaryD > 
  struct array<T, PrimaryD>
{
  typedef T type[PrimaryD];
  type data;
  T& operator[](unsigned i) { return data[i]; }

};

template<class T, unsigned PrimaryD, unsigned ... RestD > 
   struct array<T, PrimaryD, RestD...>
{
  typedef typename array<T, RestD...>::type OneDimensionDownArrayT;
  typedef OneDimensionDownArrayT type[PrimaryD];
  type data;
  OneDimensionDownArrayT& operator[](unsigned i) { return data[i]; }
}; 

int main()
{
    array<int, 2, 3>::type a4 = { { 1, 2, 3}, { 1, 2, 3} };
    array<int, 2, 3> a5{ { { 1, 2, 3}, { 4, 5, 6} } };
    std::cout << a5[1][2] << std::endl;

    array<int, 3> a6{ {1, 2, 3} };
    std::cout << a6[1] << std::endl;

    array<int, 1, 2, 3> a7{ { { { 1, 2, 3}, { 4, 5, 6 } } }};
    std::cout << a7[0][1][2] << std::endl;
}
Faisal Vali
  • 32,723
  • 8
  • 42
  • 45
  • Thank you for the reply, Faisal. That's just incredible. Very elegant. I asked mainly because I have a fixed-size multidimensional array library (Link here: http://code.google.com/p/fsma/) which provides thin wrappers around built-in 2d and 3d arrays and is analogous to std::array. I was wondering how to implement a version which allows for an arbitrary number of dimensions using variadic templates after I read the Standard Committee Paper on them. I was unaware of the power of variadic templates until I read your reply! – Ricky65 Aug 14 '11 at 19:36
  • For the 2011-Aug-14 comment by @faisal-vali, I'm not sure what you're trying to construct. Wouldn't `template arrayX` translate to something like `arrayX` given `long, 2, 3, 5` as the parameters. The variadic parameter has to expand to a comma-separated list, which nested array bounds don't qualify as. – CTMacUser Apr 23 '13 at 18:52
  • @CTMacUser Yes of course you're right - my comment is non-sense and should be stricken. – Faisal Vali Apr 24 '13 at 19:24