Gaohan Miao
Gaohan Miao

Reputation: 11

Good way to get Eigen matrix element type

I am writing a simple interface between std::vector and Eigen for my project. For a simple matrix-matrix multiplication code:

template<typename MatrixElementType1, typename MatrixElementType2>
    inline auto _matmat( const vector<MatrixElementType1>& Mat1, 
                         const vector<MatrixElementType2>& Mat2,
                         const size_t M, const size_t N, const size_t K)
    {
        using MatrixType1 = Matrix<MatrixElementType1, Dynamic, Dynamic>;
        using MatrixType2 = Matrix<MatrixElementType2, Dynamic, Dynamic>;
        Map<const MatrixType1> m1(Mat1.data(), M, N); 
        Map<const MatrixType2> m2(Mat2.data(), N, K); 
        auto rst = m1 * m2; 
        return vector<???>(rst.data(), rst.data() + rst.size());

    }

The questions is what should I use for ??? .. I know decltype(rst(0,0)) works, but is there a more elegent way? It seems decltype(rst)::value_type does not work for Eigen Matrix..

Upvotes: 1

Views: 1935

Answers (1)

ggael
ggael

Reputation: 29205

First of all, since m1*m2 returns an expression and not the result of the product, you need to evaluate it explicitly if using auto:

auto rst = (m1 * m2).eval();

Then, you can get the scalar type with decltype(rst)::Scalar. A better strategy though might be to declare a std::vector of appropriate type and size, and map it:

typedef decltype(m1*m2)::Scalar ResScalar;
vector<ResScalar> res(M,K);
Matrix<ResScalar,Dynamic,Dynamic>::Map(res.data(),M,K).noalias() = m1*m2;
return res;

Upvotes: 1

Related Questions