Yktula
Yktula

Reputation: 14849

n-dimensional vector

Let's say I want to declare a vector of a vector of a vector of a... (up to n dimensions).

Like so:

using namespace std;
// for n=2
vector<vector<int> > v2;
// for n=3
vector<vector<vector<int> > > v3;
// for n=4
vector<vector<vector<vector<int> > > > v3;

Is there a way to go about doing this for an arbitrary n with template metaprogramming?

Upvotes: 13

Views: 6049

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283931

Yes, and it's pretty straightforward.

Much like a proof by induction, we set up a recursive case and a (partially specialized) base case that ends the recursion.

template<size_t dimcount, typename T>
struct multidimensional_vector
{
    typedef std::vector< typename multidimensional_vector<dimcount-1, T>::type > type;
};

template<typename T>
struct multidimensional_vector<0,T>
{
    typedef T type;
};

multidimensional_vector<1, int>::type v;
multidimensional_vector<2, int>::type v2;
multidimensional_vector<3, int>::type v3;
multidimensional_vector<4, int>::type v4;

Upvotes: 21

Related Questions