模板矩阵类中操作符*的多重重载

Multi-overloading of operator* in template matrix class

本文关键字:重载 操作符      更新时间:2023-10-16

我有一个模板类myMatrix主要像:

template<class T, int row, int col>
class myMatrix{
   T *_mat;
public:
   template<int r, int c> using matrix_t = T[r][c];
   myMatrix(const matrix_t<row, col> &);
   myMatrix(const myMatrix<T, row, col> &);
   myMatrix &operator=( const myMatrix<T, row, col>& );
   //...
   // next is the part of * overloading
   myMatrix<T, row, col> operator*(const T& scalar);
   typename< int c2 >
   myMatrix<T, row, c2> operator*( const myMatrix<T, col, c2>& );
   typename< int c2 > 
   myMatrix<T, row, c2> operator*( const matrix_t<col, c2>& );
   typename< int r2 > 
   friend myMatrix<T, r2, col> operator*( const matrix_t<r2, row>&, const myMatrix<T, row, col>& );
   // ...
};

然后设计另一个类Reference:

template<int dim, int loop>
class Reference{
    myMatrix<int, dim, loop> _matA;
    myMatrix<int, dim, 1> _matC;
public:
    Reference(const myMatrix<int, dim, loop> &, const Matrix<int, dim, 1> &);
    Reference(const Reference<dim, loop> &);
    Reference<dim, loop> &operator=(const Reference<dim, loop> &);
    // ...
    friend Reference<1, loop> operator*(const Matrix<int, 1, dim> &alpha,
           const Reference<dim, loop> & ref)
    {
       return Reference(alpha * ref._matA, alpha * ref._matC);  // **Problem!!!**
    }
    // ...
};

当我用

这样的东西测试代码时
    const int matA[3][3] = {1,2,3,4,5,6,7};
    const int matC[3][1] = {1,2,3};
    const int alp[][3] = {1,2,2};
    Reference<3,3> ref(matA, matC);
    Matrix<int, 1, 3> alpha(alp);
   // Reference<1,3> ref_t = alp * ref;
    Reference<1,3> ref_t = alpha * ref; // **can not compile!!!**

出现问题:

二进制'*':没有找到左操作数类型为'const myMatrix'的操作符(或者没有可接受的转换)…

我的问题来了:

  1. myMatrix类的所有+4重载中,是否存在冗余?

  2. 也许只是typename< int c2 > myMatrix<T, row, c2> operator*( const myMatrix<T, col, c2>& );的重载版本可以服务于以下两个重载,因为built-in 2d-array like arr[][]可以转换为myMatrix由于我的构造函数myMatrix(const matrix_t<row, col> &); ?

  3. 编译错误的原因是什么?

编译器错误提示你做错了什么:

二进制'*':没有找到左操作数类型为'const myMatrix'的操作符

你有

operator*(const myMatrix&);

但没有

operator*(const myMatrix&) const;

所以alpha * ref不能匹配(因为alphaconst&)。

通常实现T::operator*的方法是

T& operator*=(const T&);
T operator*(const T&) const;

或者(更好的),使*操作符成为带有两个参数的自由函数(如果可能需要提升左参数,这种方法会更好)。