我目前正在编写一个矩阵类,它将能够通过模板支持任意数量的行和列。我坚持如何防止无效操作(即矩阵 1 的列数 ≠ 矩阵 2 的行数)。我当然可以存储行数和列数并在运行时进行检查,但最佳情况是我想在编译时通过“通配符”模板参数进行此检查。
换句话说...
我想这样做:
template <typename T, int R, int C>
struct mat {
T matrix[R][C];
void operator *=(const mat<T, C, [can be anything]> &other) {
/* do operation */
}
};
取而代之的是:
template <typename T, int R, int C>
struct mat {
T matrix[R][C];
int rows = R;
int columns = C;
void operator *=(const mat *other) {
if (columns != other->rows) {
/* error */
} else {
/* do operation */
}
}
};
这可能吗?如果可以,我该怎么做?
最佳答案
这对我有用
template <typename T, int R, int C>
struct mat {
T matrix[R][C];
template <int CC>
void operator *=(const mat<T, C, CC> &other) {
/* do operation */
}
};
int main()
{
mat<int, 2, 3> m1;
mat<int, 3, 4> m2;
m1 *= m2;
}
关于c++ - 如何允许通配符模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52239583/