Home C++ operator overloading <double> - <Matrix>
Reply: 1

C++ operator overloading <double> - <Matrix>

Michael
1#
Michael Published in 2017-12-07 17:40:54Z

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;
  }
}
Remy Lebeau
2#
Remy Lebeau Reply to 2017-12-07 17:51:30Z

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;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.331238 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO