I\'m trying to implement a hypercubeclass, that is, multidimensional vectors. I have a problem generalizing it. I\'m able to make one for a three dimensional hypercube, but
For this to work, you need recursive inheritence to provide the correct vector type and the initialization function. Both work recursively, for which I created a little helper struct called hcube_info
:
// hypercube.h
#include
template
struct hcube_info;
template<>
struct hcube_info<1>
{ // base version
typedef std::vector type;
static type init(unsigned innerdim, int value = 0){
return type(innerdim, value);
}
};
template
struct hcube_info
{ // recursive definition, N dimensions
private:
typedef hcube_info base;
typedef typename base::type btype;
public:
typedef std::vector type;
static type init(unsigned innerdim, int value = 0){
return type(innerdim, base::init(innerdim, value));
}
};
As you can see, recursion all the way to the one dimensional base case. We also need to recursively initialize the vector to pass the inner dimension all the way through.
And now the real class, a nice interface around the hcube_info
:
template
struct hypercube
{
private:
typedef hcube_info info;
typedef typename info::type vec_type;
public:
typedef typename vec_type::value_type value_type;
typedef typename vec_type::size_type size_type;
explicit hypercube(unsigned innerdim, unsigned value = 0)
: c(info::init(innerdim, value))
{
}
value_type& operator[](unsigned i){
return c[i];
}
size_type size() const{ return c.size(); }
private:
vec_type c;
};
Test program:
#include "hypercube.h"
#include
int main(){
hypercube<4> c(5);
unsigned s = c.size() * // dim 1
c[0].size() * // dim 2
c[0][0].size() * // dim 3
c[0][0][0].size(); // dim 4
std::cout << s << '\n'; // outputs: 625 -> 5 * 5 * 5 * 5 -> 5^4
}