如何使模板函数运算符隐式推导模板参数?

问题描述

我有这段代码需要编译:

int main () {
    const Matrix<int,3,2> m1; // Creates 3*2 matrix,with all elements set to 0;
    Matrix<int,3> m2(4); // Creates 3*3 matrix,with all elements equals to 4;
    const Matrix<int,3> m3 = m2; // copy constructor may take O(MN) and not O(1).
    cout << m3 * m1 << endl; // You can choose the format of matrix printing;

我已经为模板矩阵实现了 operator<<。 问题是创建 operator* 以便使用 m3.rows 和 m1.cols 的模板参数创建一个新矩阵,问题是在 operator* 的签名中定义返回类型。

我试过了:

Matrix<int,lhs.rows,rhs.cols> operator *(const MatrixBase& lhs,const MatrixBase& rhs)
Matrix<?> res; // not sure how to define it
{
    for (int i = 0; i < lhs.get_columns(); i++)
    {
        for (int j = 0; j < rhs.get_rows(); j++)
        {
            for (int k = 0; k < lhs.get_columns(); k++)
            {
                res[i][j] = lhs[i][k] * rhs [k][j];
            }
        }
    }
}

MatrixBase 类只是 Matrix 派生自的非模板抽象类,尝试使 operator* 泛型。 问题是 lhsrhs 尚未初始化并且无法编译,我想将 operator* 作为 Matrix 的方法,但我仍然坚持返回类型。 我知道该模板是由预处理器确定的,但我确信有一种方法可以让它运行。

解决方法

您的问题缺少关于 MatrixBase 是什么的一些信息,但如果我们只查看您的 Matrix 类,您需要一个模板函数来执行此操作。在那里你可以推导出类的模板参数并使用它来计算结果类型。

template <typename T,int LRows,int LCols,int RRows,int RCols>
Matrix<T,LRows,RCols> operator*(const Matrix<T,LCols>& lhs,const Matrix<T,RRows,RCols>& rhs) {
    static_assert(LCols == RRows,"Invalid matrix multiplication");
    Matrix<T,RCols> result;
    // ... do the calculations
    return result;
}