-2

Let's suppose that we want to subtract some value from a given matrix. How could/should I overload that operator.

main.cpp

Matrix<double> m(10, 5);

auto r = 1.0 - m; //error: return type specified for 'operator double'

matrix.hpp

template <typename T>
class Matrix {
public:
  Matrix operator double(T val) {
    Matrix tmp(rows, cols);

    for (unsigned int i = 0; i < rows; i++)
      for (unsigned int j = 0; j < cols; j++) {
        const unsigned int idx = VecToIdx({i, j});
        tmp[idx] = val - this[idx];
      }

    return tmp;
  }
}
Michael
  • 177
  • 2
  • 15

1 Answers1

1

Your code is trying to subtract a Matrix from a double, but your question asks to subtract a double from a Matrix instead. Those are two different operations. What do you really want to do?

In the latter case, you need to overload the subtraction operator, not the conversion operator, eg:

template <typename T>
class Matrix {
public:
    Matrix operator- (T val) {
        Matrix tmp(rows, cols);
        for (unsigned int i = 0; i < rows; i++)
            for (unsigned int j = 0; j < cols; j++) {
                const unsigned int idx = VecToIdx({i, j});
                tmp[idx] = (*this)[idx] - val;
            }
        return tmp;
    }
};

Matrix<double> m(10, 5);

auto r = m - 1.0;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770