抱歉,标题很尴尬,很难用文字来表达。 我想知道的是:
假设我有一个模板类,比如
template<typename T, int height, int width> class GMatrix
我想重载 * 运算符以便将矩阵相乘。当然,所讨论的两个矩阵不需要具有相同的宽度和高度,只要右侧矩阵的高度等于左侧矩阵的宽度即可。
基本上我希望这种功能成为可能:
GMatrix<float, 3, 3> left;
GMatrix<float, 3, 6> right;
GMatrix<float, 3, 6> result = left * right;
这样的函数可以写吗?如果是这样,它的语法可能是什么样的?
感谢阅读。
最佳答案
一种可能的方法是使 operator*
成为两个操作数维度中的模板函数,如下例所示:
template<typename T, int height, int width>
class GMatrix {
};
template<typename T, int h1, int w1, int h2, int w2>
GMatrix<T, h1, w2>
operator*(GMatrix<T, h1, w1> const& a, GMatrix<T, h2, w2> const& b) {
return GMatrix<T, h1, w2>(); // Or do something else
}
int main() {
GMatrix<float, 3, 3> left;
GMatrix<float, 3, 6> right;
GMatrix<float, 3, 6> result = left * right;
}
您还可以在参数级别强制执行矩阵维度:
template<typename T, int h1, int wh, int w2>
GMatrix<T, h1, w2>
operator*(GMatrix<T, h1, wh> const& a, GMatrix<T, wh, w2> const& b) {
return GMatrix<T, h1, w2>(); // Or do something else
}
关于c++ - 是否可以编写一个函数,它接受具有不同初始化的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30623791/