Writing an operator function to multiply a custom template matrix class with a scalar.
template <typename T>
class Matrix {
public:
Matrix() //default constructor
Matrix(size_t Row, size_t Col); //initialize with zeros of row,col
explicit Matrix(const vector<vector<T>> matElems); // create a matrix from vec<vec>>
friend Matrix<ret_type> operator*(const Matrix<mat_type> matrix,
const scalar_type scalar);
private:
vector<vector<T>> elements;
std::size_t nRows;
std::size_t nCols;
};
template <typename mat_type, typename scalar_type,
typename ret_type = decltype(mat_type() * scalar_type())>
Matrix<ret_type> operator*(const Matrix<mat_type> matrix,
const scalar_type scalar) {
Matrix<mat_type> copy_matrix = matrix;
Matrix<ret_type> result = static_cast<Matrix<ret_type>>(copy_matrix);
for (vector<ret_type> v : result.elements) {
std::transform(v.begin(), v.end(), v.begin(),
std::bind1st(std::multiplies<ret_type>(), scalar));
}
return result;
}
Error: no matching function for call to ‘Matrix::Matrix(Matrix&)’ on the line Matrix<ret_type> result = static_cast<Matrix<ret_type>>(copy_matrix)
Reason of doing this is to cast an int type matrix to double if it is multiplied by a double scalar.
Aucun commentaire:
Enregistrer un commentaire