如何允许通配符模板参数

How To Allow Wildcard Template Argument

本文关键字:参数 通配符 何允许      更新时间:2023-10-16

我目前正在编写一个矩阵类,该类能够通过模板支持任意数量的行和列。我被困在如何防止无效操作(即矩阵 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;
}

define template《int K》mat《T,R,K》&operator*(const mat《T, C,K》& other(。