Search code examples
c++templateseigeneigen3

Generic Eigen Matrix/Vector object transfer to a custom matrix/vector container


So I have a custom made matrix/vector container (denoted MyContainer for simplicity) suited to a special purpose, and want to implement functionality for transferring the data of Eigen objects (Matrices, fixed, dynamic etc..) to my custom container. Thus I want to create a function similar to (illustrated with Eigen::MatrixXd)

template<class T>
void assign_eigen_object(MyContainer<T> &lhs, const Eigen::MatrixXd &rhs)
{
    int n_rows = rhs.rows(), n_cols = rhs.cols();
    lhs.resize(n_rows, n_cols);
    for (int i = 0; i < n_rows; i++)
    {
        for (int j = 0; j < n_cols; j++)
        {
            lhs(i, j) = (T)rhs(i, j);
        }
    }
}

Is it then possible to create a templated function which takes into account all Eigen types (float dynamic matrix, double dynamic matrix, float fixed matrix, float partially fixed matrix etc..)?, or do I need to overload the function for the relevant objects? Maybe Eigen::Map can help me?


Solution

  • It should be as simple as changing the definition to this:

    template<class T, typename TEigenType>
    void assign_eigen_object(MyContainer<T> &lhs, const TEigenType &rhs)
    { ...
    

    However, with the correct memory layout of MyContainer, you may be able to do even better and replace the nested loops with a single std::copy.


    EDIT:

    You might also want to add something like this to avoid possible missuse. I'm not entirely sure it will work with all eigen types though:

    static_assert(std::is_same_v<std::decay_t<T>,
                                 std::decay_t<typename TEigenType::value_type> >);