Yau*_*nka 3 c++ templates vector
我想要一些 N 维向量的简单包装器,例如vector<vector<vector<double>>>等。更准确地说,我想在我的代码中编写类似NDvector<3,double>而不是vector<vector<vector<double>>>. 实现这一点的最优雅的方法是什么?我的想法是写一些类似的东西
template<size_t N, typename T>
using NDvector = vector<NDvector<N-1, T>>;
template<typename T>
using NDvector<1,T> = vector<T>;
Run Code Online (Sandbox Code Playgroud)
但是,这个不能编译。
类型别名不能部分特化;
您可以添加一个可以部分专门化的类模板。例如
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;
Run Code Online (Sandbox Code Playgroud)
然后你可以用它作为
NDvector<3, double> v3d; // => std::vector<std::vector<std::vector<double>>>
Run Code Online (Sandbox Code Playgroud)