【发布时间】:2020-08-02 00:07:48
【问题描述】:
我正在尝试制作一个固定大小的矩阵类。目的是让它继承或利用std::array 的std::array:
template <size_t Rows, size_t Columns, class T=double>
struct Matrix : public std::array<std::array<T, Columns>, Rows> {
};
我想提供一个可以自动推断大小的初始化程序,就像 C++17(我正在使用的)中的 std::array 一样。我也可以使用函数来制作Matrix,而不是使用类模板参数推导。
// What I want, but does not work:
Matrix matrix {{1., 2.},
{3., 4.}};
// Or:
auto matrix = MakeMatrix ({1., 2.},
{3., 4.});
我没能让其中任何一个成为可能。相反,只有以下工作:
// Requires specifying the size and repeating `std::array`, both undesired
Matrix<2,2> mat {
std::array{1., 2.},
std::array{3., 4.}
};
// OR this, which requires specifying the size and is generally confusing
Matrix<2,2> mat2 {1., 2.,
3., 4.};
我尝试使用可变参数模板,但这也没有吸引编译器:
template<class... Args>
auto MakeMatrix (Args... args) {
return Matrix{ std::array {args} ... };
}
// This causes compiler error:
// error: no matching function for call to 'MakeMatrix'
// candidate function [with Args = <>] not viable: requires 0 arguments, but 2 were provided
auto matrix = MakeMatrix ({1., 2.},
{3., 4.});
// This causes compiler error
// error: no viable constructor or deduction guide for deduction of template arguments of 'Matrix'
// note: in instantiation of function template specialization 'MakeMatrix<std::__1::array<double, 2>, std::__1::array<double, 2> >'
// note: note: candidate function template not viable: requires 0 arguments, but 2 were provided
auto matrix = MakeMatrix (std::array {1., 2.},
std::array {3., 4.});
我也考虑过使用std::initializer_list<std::initializer_list<T>>,但是据我所知这些不支持固定大小,我希望在编译时确定大小。
关于如何做到这一点的任何想法,还是用当前的 C++ 机制是不可能的?
【问题讨论】:
-
避免从 std 类型继承——疯狂去那里。使用组合(封装一个 std::array 就可以了)。
-
请注意,标准容器并非设计为具有多态行为。标准容器的公共继承使您面临潜在风险。 Link。您可以私下继承,拥有一个
std::array成员,或者如果Matrix非常薄,请改用using类型别名。 -
查看this question 获取
make_array获取一维std::array;我希望它可以推广到二维。一般来说,我建议不要使用这种东西;可变参数模板往往会变得混乱。
标签: c++ templates matrix c++17 stdarray