I have a class template that has a boost matrix as a private member variable. The matrix data type is determined by the class type when constructed. This class has a member function that is supposed to add a constant to the member matrix. The constant is consistent with the matrix data type. I am having trouble writing an overloaded operator that will return an updated member matrix for arbitrary constant values. Currently, another member function does this addition. My code is as follows;
/*content from main.cpp compiled with `g++ -o main main.cpp` */
#include <iostream>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
using namespace boost::numeric::ublas;
using namespace std;
template <typename T>
class MTool
{
private:
matrix<T> m_ME;
public:
MTool(int N, int M) { m_ME.resize(M, N); } // constructor
~MTool() { m_ME.clear(); } // destructor
void PutMatValues(); // insert values into member matrix
void AddConst(const T &k) { m_ME+=k; } // add a constant to member matrix
void PrintMat() { cout << "The ME " << endl << m_ME << endl; } // print the member matrix
// overloaded operator function
matrix<T> operator+ <> (const T& kvalue) { return (m_ME+kvalue); }
};
template<typename T>
void MTool<T>::PutMatValues()
{
for (unsigned row=0; row<m_ME.size1(); row++)
for (unsigned col=0; col<m_ME.size2(); col++)
m_ME(row,col)=static_cast<T> (row*col);
}
int main()
{
MTool<double> mymat(5, 3);
double dk=123.67001;
mymat.PutMatValues();
mymat.PrintMat();
mymat.AddConst(dk);
mymat.PrintMat();
return 0;
}
Some of the compiler errors I get are
error: template-id ‘operator+<>’ in declaration of primary template
error: no match for ‘operator+=’ in ‘((MTool*)this)->MTool::m_ME += k’
I am rather new to C++ templates and classes and am sure there is something fundamental missing from my approach. Any suggestions would highly appreciated.
The first is just a syntax error, this member operator+ would be written as
although it’s somewhat unusual to see a binary plus operator as a member function: it’s almost always implemented as a non-member, so that you could write expressions
c + Mas well asM + c.The second error is simply pointing out that
boost::numeric::ublas::matrixhas nooperator+=that takes a scalar argument. There is also nooperator+that can add a matrix and a scalar, so the expressionm_ME+kvaluein your operator+ won’t compile either.Addition is only defined between matrices of equal shape. If you’re adding the scalar to every element of the matrix, you’re going to need to write that, something like: