我有一个矩阵类的开始。这是代码-
template<int h, int w = h>
class mat {
public:
mat() : values(h, std::vector<double>(w)) {
if (w == h) {
int x = 0;
for (int y = 0; y < h; y++) {
values[y][x] = 1;
x++;
}
}
}
mat(std::initializer_list<std::vector<double>> matvals){
values = matvals;
}
mat(int val) : values(h, std::vector<double>(w, val)) {}
mat(const mat& m) {
values = m.values;
}
mat(mat&& m) {
values = std::move(m.values);
}
int width() {
return w;
}
int height() {
return h;
}
template<int mh, int mw = mh>
auto operator*(const mat<mh, mw>& m) -> mat<h, mw> const {
if (w != mh) throw std::logic_error{ "Matrices cannot be multiplied" };
mat<h, mw> temp;
std::vector<double> mcol(mh);
for (int y = 0; y < mw; y++) {
for (int mx = 0; mx < mw; mx++) {
for (int my = 0; my < mh; my++) {
mcol[my] = m.values[my][mx];
}
temp.values[y % h][mx] = dot(values[y % h], mcol);
}
}
return temp;
}
mat operator+(const mat& m) const {
mat temp;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
temp.values[y][x] = values[y][x] + m.values[y][x];
}
}
return temp;
}
std::vector<double>& operator[](int y) {
return values[y];
}
mat& operator=(const mat& m) {
values = m.values;
return *this;
}
mat& operator=(mat&& m) {
values = std::move(m.values);
return *this;
}
private:
std::vector<std::vector<double>> values;
template<int mw, int mh>
friend class mat;
};
到目前为止,这是该类的使用方式-
mat<2, 4> mat1 = {
{1, 2, 3, 4},
{5, 6, 7, 8},
};
mat<4, 3> mat2 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
auto mat3 = mat1 * mat2;
注意到冗余了吗?如果用户想要使用std::initializer_list
构造函数创建矩阵,那么他们必须首先在模板参数中指定宽度和高度。此外,如果他们使用std::initializer_list
的尺寸与模板参数中指定的尺寸不同,那么行为将是未定义的。非类型模板参数如何写推演指南?我知道如何使用基本模板来做到这一点,但是我尝试像您一样尝试做的所有事情通常都会产生许多编译器错误。这是期望的行为-
mat mat1 = {
{1, 2, 3, 4},
{5, 6, 7, 8},
};
mat mat2 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
auto mat3 = mat1 * mat2;
编辑:任何想要制作矩阵类的人都不应该制作宽度和高度模板参数。它只是不必要地使事情复杂化。