我有一个 N 维 Matrix 类,它有一个带参数包的构造函数。是否可以根据参数包中的值设置 std::array
成员变量的大小?据我了解,参数包中的值应该在编译时已知。
template<size_t N>
class Matrix {
public:
template<typename... Exts>
Matrix(Exts... exts) : dimSizes{exts...} { }
private:
std::array<size_t, N> dimSizes;
std::array<float, N> data;
// e.g something like this: std::array<float, dimSizes[0]> data;
};
int main(void) {
Matrix<3> mat(2, 3, 2);
return 0;
}
最佳答案
Is it possible to set the size of the
std::array
member variable depending on the values in the parameter pack?// e.g something like this:
std::array<float, dimSizes[0]> data;
不,据我所知,完全按照你的想法是不可能的。
因为这样,同一类的不同实例将包含名称相同但类型不同的成员。严格禁止在 C++ 等强类型语言中使用。
如果你想要一个std::array
尺寸不同,你必须区分类型;所以第二个维度 std::array
必须是模板参数。
显然您可以用 std::array
代替使用不依赖于大小的容器;正如 Piotr Skotnicki 所建议的,一个可能的解决方案是 std::vector
关于c++ - 如何通过参数包参数设置 std::array 大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470411/