Search code examples
c++boostsparse-matrixublas

API that handles boost ublas sparse OR dense matrices


I am a bit perplexed by the Boost ublas documentation. It does not seem clear to me that the sparse and dense matrix classes share a common parent class---which I believe is by design. But then how can I design an API that can accept either sparse or dense matrix, assuming that it need only operate on entries of the matrix using the operator() accessor, say. For example, something like this:

float doMatrixMath(matrix_base<float> m) 
{
  return m(1,1)+m(2,2);
}

Perhaps my thinking about this is wrong-headed. Any guidance regarding how to think about the object modeling of ublas classes would be appreciated!


Solution

  • Templates unfortunately. You can use a very generic type, or dig in and find something more concrete, but the general idea is:

    template< typename MatrixType >
    float doMatrixMath(MatrixType m) 
    {
      return m(1,1)+m(2,2);
    }
    

    Of course this can be enhanced with a more concrete type and return value detection...