1
votes

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?

2

2 Answers

1
votes

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> >);
1
votes

You probably want to define the function as a template like Benny K's answer.

If you have access to the raw storage of MyContainer (e.g. MyContainer::data()) you can use Eigen::Map for the implementation. Something like this:

Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>> lhs_map(lhs.data(), n_rows, n_cols);
lhs_map = rhs.cast<T>();

Eigen::Map can be adapted to fit almost any regular memory layout (strides, column/row major, etc.) as long as it's a single block of memory.