Using safe non-const function in a const function

242 views Asked by At

I need to use MatrixSequence::matrix in my stream operator ostream& operator<<(ostream &outputStream, const MatrixSequence &sequence), so I need it to be const. However it uses Map<Matrix> which doesn't seems to be const safe. I got the error

matrixsequence.cpp:38: error: invalid conversion from 'const double*' to 'Eigen::Map<Eigen::Matrix<double, -1, -1> >::PointerArgType {aka double*}' [-fpermissive]

when I add the final const keywrk to MatrixSequence::Matrix

typedef Eigen::MatrixXd Matrix;
typedef Eigen::Map Map;

Map<Matrix> MatrixSequence::matrix(const unsigned int i) const {
    assert(i <= shapes_->size());
    const double* beginning = &data_.at(beginning_matrix->at(i));
    const tuple<int, int>& shape = shapes_->at(i);
    return Map<Matrix>(beginning, get<0>(shape), get<1>(shape));
}

ostream& operator<<(ostream &outputStream,
                    const MatrixSequence &sequence) {
    for(unsigned int i=0; i<sequence.size(); i++) {
        outputStream << "\n" << sequence.matrix(i) << "\n";
    }
    return outputStream;
}
1

There are 1 answers

0
ggael On

As suggested in the comments, a cleaner solution is to return a Map<const MatrixXd> as in the self-contained example:

#include <Eigen/Core>
using namespace Eigen;

struct Foo {
  double data[10];

  Eigen::Map<const MatrixXd> foo() const {
    Map<const MatrixXd> out(data, 5, 2);
    return out;
  }
};

int main() {
  Foo f;
  MatrixXd A = 2 * f.foo();;
}