Yauhen Yakimenka
Yauhen Yakimenka

Reputation: 499

C++ templated alias of N-dimensional vector

I want some simple wrapper for N-dimensional vectors like vector<vector<vector<double>>>, etc. More precisely, I would like to write in my code something like NDvector<3,double> instead of vector<vector<vector<double>>>. What would be the most elegant way to implement this? My idea is to write something like

template<size_t N, typename T>
using NDvector = vector<NDvector<N-1, T>>;

template<typename T>
using NDvector<1,T> = vector<T>;

However, this one doesn't compile.

Upvotes: 3

Views: 267

Answers (1)

songyuanyao
songyuanyao

Reputation: 173044

Type alias can't be partial specialized;

It is not possible to partially or explicitly specialize an alias template.

You can add a class template which could be partial specialized. e.g.

template<size_t N, typename T>
struct NDvector_S {
    using type = vector<typename NDvector_S<N-1, T>::type>;
};
template<typename T>
struct NDvector_S<1, T> {
    using type = vector<T>;
};

template<size_t N, typename T>
using NDvector = typename NDvector_S<N, T>::type;

then you can use it as

NDvector<3, double> v3d; // => std::vector<std::vector<std::vector<double>>>

Upvotes: 7

Related Questions