且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

定义一个未知深度/维度的 C++ 模板

更新时间:2023-11-11 16:59:40

当然,C++11 具有模板的可变长度参数列表.即使没有 C++11,您也可以使用专业化,如果您的所有维度都具有相同的类型:

Certainly, C++11 has variable length parameter lists for templates. Even without C++11 you can use specialisation, if all your dimensions have the same type:

template <typename T, unsigned nest>
struct Bin {
  std::vector<Bin<T, (nest-1)> > bins;
};

template <typename T>
struct Bin<T,0> {
  T content;
};

您只能在运行时指定一定程度的维度.如果它受固定值的约束,您甚至可以动态选择适当的类型.但是,请考虑使用一维向量而不是多维锯齿状向量!

You can only specify the dimension at runtime to a certain degree. If it is bound by a fixed value you can select the appropriate type even dynamically. However, consider using a one-dimensional vector instead of a multi-dimensional jagged vector!