c++ - Multi-overloading of operator* in template matrix class -


i have template class of mymatrix like:

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 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>& );    // ... }; 

then design class 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!!!**     }     // ... }; 

when test codes

    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!!!** 

the problem occurs:

binary '*': no operator found takes left-hand operand of type 'const mymatrix' ( or there no acceptable conversion )...

then here come questions:

  1. of +4 overloadings in class mymatrix, if there redundancies?

  2. maybe overloading version of typename< int c2 > mymatrix<t, row, c2> operator*( const mymatrix<t, col, c2>& ); can service following 2 overloads since built-in 2d-array arr[][] can convert mymatrix due constructor mymatrix(const matrix_t<row, col> &);?

  3. what reason compiling error?

the compiler error says you've done wrong:

binary '*': no operator found takes left-hand operand of type 'const mymatrix'

you have

operator*(const mymatrix&); 

but no

operator*(const mymatrix&) const; 

so alpha * ref can't match (because alpha const&).

the usual way implement t::operator* is

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

or (better), make * operator free function 2 arguments (this can work better if might need promote left-hand argument).


Comments