Search code examples
c++functionsparse-matrixeigen

C++ function that takes args Eigen sparse matrices


Eigen library provides/suggests numerous ways to pass a dense matrix in a function, so that it works for a different types that share the same base, and avoids copying (i.e. Ref<>, template expressions).

However, I haven't found anything equivalent for sparse matrices in either eigen documentation or online.

I basically have the following question: How can I write a function with a generic interface so it can be called with both SparseMatrix or MappedSparseMatrix objects, of potentially different template arguments, without copying?

I have tried template expression of SparseMatrixBase withe derived arguments but I couldn't make it work.

A simple example code will be appreciated.


Solution

  • Simply write a template function taking any SparseMatrixBase<Derived>, for instance:

    template<typename Derived>
    void foo(const SparseMatrixBase<Derived> &a_mat) {
        const Derived &mat(a_mat.derived());
        SparseMatrix<typename Derived::Scalar> tr_mat = mat.transpose();
    }