首页 > 解决方案 > Eigen 自定义类和函数参数

问题描述

我正在尝试使用 Eigen 替换我的代码中当前使用的矩阵库。我有几个像这样的类,将自定义方法添加到基矩阵类。在这个例子中,我用 Eigen 替换了父类:

#include <iostream>
#include <eigen3/Eigen/Dense>

class MyVectorType: public Eigen::Matrix<double, 3, 1> {
public:
    MyVectorType(void) :
            Eigen::Matrix<double, 3, 1>() {
    }
    typedef Eigen::Matrix<double, 3, 1> Base;
    // This constructor allows you to construct MyVectorType from Eigen expressions
    template<typename OtherDerived>
    MyVectorType(const Eigen::MatrixBase<OtherDerived>& other) :
            Eigen::Matrix<double, 3, 1>(other) {
    }
    // This method allows you to assign Eigen expressions to MyVectorType
    template<typename OtherDerived>
    MyVectorType & operator=(const Eigen::MatrixBase<OtherDerived>& other) {
        this->Base::operator=(other);
        return *this;
    }
    void customMethod() {
        //bla bla....
    }
};

最大的问题是在方法中管理自定义类并不容易。例子:

void foo(MyVectorType& a) {
    ....
    a.customMethod();
}

void foo(Eigen::Ref<MyVectorType::Base> a) {
    ....
    a.customMethod(); <---can't call customMethod here
}

Eigen::Matrix<double, -1, -1, 0, 15, 15> m(3,1);
foo(m); <---can't call it with m;
Eigen::Map<Matrix<double, 3, 1> > map(m.data(), 3, 1);
Eigen::Ref<Matrix<double, 3, 1> > ref(map);
foo(ref); <---it works but I can't call custom method

通常 Eigen 提供 Ref 模板类,但我不能将它与自定义类一起使用,因为如果我使用 Ref,在此示例中我将无法在 foo 中调用 customMethod,我应该在我的示例中使用 Eigen::Ref。避免使用 Ref 是一个大问题,因为使用 Map 和 Ref Eigen 对象对于将动态矩阵转换为固定矩阵并执行其他转换操作非常重要。最后一个问题:在这种情况下使用 Eigen 的最佳策略是什么?

标签: c++eigen

解决方案


至少有以下三种方法:

  1. 通过插件机制摆脱MyVectorType并成为customMethod成员。MatrixBase

  2. 摆脱MyVectorType并做customMethod一个免费的功能。

  3. Eigen::Ref<MyVectorType>通过让它继承Ref<MyVectorType::Base>及其构造函数,添加一个customMethod方法并通过调用内部自由函数分解这两个方法来进行特殊化customMethod_impl


推荐阅读