Home > Blockchain >  Inherit from boost::matrix
Inherit from boost::matrix

Time:12-09

I would like to inherit from boost::matrix to enrich with some methods. I started with this :

#include <boost/numeric/ublas/matrix.hpp>

using namespace boost::numeric::ublas;

class MyMatrix : public matrix<double>
{
public:
    MyMatrix() : matrix<double>(0, 0) {}

    MyMatrix(int size1, int size2) : matrix<double>(size1, size2) {}

    MyMatrix(MyMatrix& mat) : matrix<double>(mat) {}

    MyMatrix(matrix<double>& mat) : matrix<double>(mat) {}

    MyMatrix& operator=(const MyMatrix& otherMatrix)
    {
        (*this) = otherMatrix;
        return *this;
    }
};

that allows me do to stuff like:

MyMatrix matA(3, 3);
MyMatrix matB(3, 3);
MyMatrix matC(matA);

but I may missed something because I am not able do to:

MyMatrix matD(matA * 2);
MyMatrix matE(matA   matB);

that causes:

error: conversion from 'boost::numeric::ublas::matrix_binary_traits<boost::numeric::ublas::matrix<double>, boost::numeric::ublas::matrix<double>, boost::numeric::ublas::scalar_plus<double, double> >::result_type {aka boost::numeric::ublas::matrix_binary<boost::numeric::ublas::matrix<double>, boost::numeric::ublas::matrix<double>, boost::numeric::ublas::scalar_plus<double, double> >}' to non-scalar type 'MyMatrix' requested

How can I use the methods from boost::matrix without redefining all of them inside MyMatrix ?

CodePudding user response:

You don't need any of your additions to make this work:

MyMatrix matA(3, 3);
MyMatrix matB(3, 3);
MyMatrix matC(matA);

MyMatrix matD(matA * 2);
MyMatrix matE(matA   matB);

You only need to bring the boost::numeric::ublas::matrix<double> constructors and assignment operators into your derived class:

#include <boost/numeric/ublas/matrix.hpp>

class MyMatrix : public boost::numeric::ublas::matrix<double> {
public:
    using matrix<double>::matrix;    // use the constructors already defined
    using matrix<double>::operator=; // and the operator=s already defined

    // put your other additions here (except those you had in the question)
};

Demo

  • Related