For example in 3 dimensions, I would normally do something like
vector<vector<vector<T>>> v(x, vector<vector<T>>(y, vector<T>(z, val)));
However this gets tedious for complex types and in large dimensions. Is it possible to define a type, say, tensor, whose usage would be like so:
tensor<T> t(x, y, z, val1);
t[i][j][k] = val2;
>Solution :
It’s possible with template metaprogramming.
Define a vector NVector
template<int D, typename T>
struct NVector : public vector<NVector<D - 1, T>> {
template<typename... Args>
NVector(int n = 0, Args... args) : vector<NVector<D - 1, T>>(n, NVector<D - 1, T>(args...)) {
}
};
template<typename T>
struct NVector<1, T> : public vector<T> {
NVector(int n = 0, const T &val = T()) : vector<T>(n, val) {
}
};
You can use it like this
const int n = 5, m = 5, k = 5;
NVector<3, int> a(n, m, k, 0);
cout << a[0][0][0] << '\n';
I think it’s clear how it can be used. Let’s still say NVector<# of dimensions, type> a(lengths of each dimension separated by coma (optional)..., default value (optional)).